Untitled

mail@pastecode.io avatar
unknown
java
13 days ago
1.4 kB
1
Indexable
Never
import java.util.HashMap;

class HelloWorld {
    public static int findMaxLength(int[] nums) {
        // Initialize variables
        HashMap<Integer, Integer> map = new HashMap<>();
        map.put(0, -1);
        int maxLength = -1;
        int count = 0;

        // Iterate through the array
        for (int i = 0; i < nums.length; i++) {
            // Adjust the count based on the value
            count += (nums[i] == 1) ? 1 : -1;

            // Check if this count has been seen before
            if (map.containsKey(count)) {
                // Update the maximum length if this subarray is longer
                maxLength = Math.max(maxLength, i - map.get(count));
            } else {
                // Store the first occurrence of this count
                map.put(count, i);
            }
        }

        // If no subarray was found, return -1
        return (maxLength == 0) ? -1 : maxLength;
    }

    public static void main(String[] args) {
        // Sample test cases
        int[] case1 = {0, 0, 0, 0, 0};
        int[] case2 = {1, 0, 1, 0, 0};
        int[] case3 = {0, 1, 1, 1, 1};

        System.out.println(findMaxLength(case1)); // Output: -1
        System.out.println(findMaxLength(case2)); // Output: 4
        System.out.println(findMaxLength(case3)); // Output: 2
    }
}
Leave a Comment