LeetCode in Kotlin

525. Contiguous Array

Medium

Given a binary array nums, return the maximum length of a contiguous subarray with an equal number of 0 and 1.

Example 1:

Input: nums = [0,1]

Output: 2

Explanation: [0, 1] is the longest contiguous subarray with an equal number of 0 and 1.

Example 2:

Input: nums = [0,1,0]

Output: 2

Explanation: [0, 1] (or [1, 0]) is a longest contiguous subarray with equal number of 0 and 1.

Constraints:

Solution

class Solution {
    fun findMaxLength(nums: IntArray): Int {
        for (i in nums.indices) {
            if (nums[i] == 0) {
                nums[i] = -1
            }
        }
        val map: HashMap<Int, Int> = HashMap()
        map[0] = -1
        var ps = 0
        var len = 0
        for (i in nums.indices) {
            ps += nums[i]
            if (!map.containsKey(ps)) {
                map[ps] = i
            } else {
                len = Math.max(len, i - map[ps]!!)
            }
        }
        return len
    }
}
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy