Skip to main content

Command Palette

Search for a command to run...

maxlength sub

Published
1 min readView as Markdown
class Solution {
    public int findMaxLength(int[] nums) {
        // Convert 0s to -1s
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] == 0) nums[i] = -1;
        }

        HashMap<Integer, Integer> map = new HashMap<>();
        int sum = 0, maxLength = 0;

        for (int i = 0; i < nums.length; i++) {
            sum += nums[i];

            // Handle case where sum == 0 (subarray starts from index 0)
            if (sum == 0) {
                maxLength = i + 1;
            }

            if (map.containsKey(sum)) {
                int prevIndex = map.get(sum);
                maxLength = Math.max(maxLength, i - prevIndex);
            } else {
                map.put(sum, i);
            }
        }

        return maxLength;
    }
}

More from this blog

Amit singh's blog

235 posts