aboutsummaryrefslogtreecommitdiff
path: root/contiguous_array.py
diff options
context:
space:
mode:
authorjack <[email protected]>2024-06-14 13:13:15 -0600
committerjack <[email protected]>2024-06-14 13:13:15 -0600
commitd343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa (patch)
tree96df922dae2a5073d9a50ea70c7aae6aa37e3ebe /contiguous_array.py
downloadleetcode-d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa.tar.gz
leetcode-d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa.zip
initial
Diffstat (limited to 'contiguous_array.py')
-rw-r--r--contiguous_array.py32
1 files changed, 32 insertions, 0 deletions
diff --git a/contiguous_array.py b/contiguous_array.py
new file mode 100644
index 0000000..8bd17a5
--- /dev/null
+++ b/contiguous_array.py
@@ -0,0 +1,32 @@
+# 525. Contiguous Array
+
+"""
+given a binary array 'nums' return the maximum length of a contiguous
+subarray with an equal number of 0 and 1.
+"""
+
+
+class Solution(object):
+ def findMaxLength(self, nums):
+ """
+ :type nums: List[int]
+ :rtype: int
+ """
+ cnt, max_length = 0, 0
+ table = {0: 0}
+ for idx, n in enumerate(nums, 1):
+ if n == 0:
+ cnt -= 1
+ else:
+ cnt += 1
+ if cnt in table:
+ max_length = max(max_length, idx - table[cnt])
+ else:
+ table[cnt] = idx
+ return max_length
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.findMaxLength([0, 1]))
+ print(obj.findMaxLength([0, 1, 0]))