Untitled
import java.util.HashMap; public class ContiguousArray { public int findMaxLength(int[] nums) { // Replace 0 with -1 to handle the sum logic int maxLength = 0; int prefixSum = 0; HashMap<Integer, Integer> map = new HashMap<>(); // Add a base case to handle the entire array summing to zero map.put(0, 0); for (int i = 0; i < nums.length; i++) { prefixSum += (nums[i] == 0) ? -1 : 1; if (map.containsKey(prefixSum)) { // If prefixSum exists, calculate the subarray length maxLength = Math.max(maxLength, i+1 - map.get(prefixSum) + 1); } else { // Otherwise, store the first occurrence of the prefixSum map.put(prefixSum, i+1); } } return maxLength; } public static void main(String[] args) { ContiguousArray solution = new ContiguousArray(); System.out.println(solution.findMaxLength(new int[]{0, 1})); // Output: 2 System.out.println(solution.findMaxLength(new int[]{0, 1, 0})); // Output: 2 } }
Leave a Comment