Untitled
unknown
java
a year ago
1.4 kB
5
Indexable
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 } }
Editor is loading...
Leave a Comment