Leetcode question: Given a binary array nums, return the maximum length of a contiguous subarray with an equal number of 0 and 1.
Leetcode entered a very long input of to the function and its IDE couldn't handle the inflated memory use
(update: added 2 better versions)
In the first versions I appended all the possible subarrys to a 2d list. I removed that in these version. Now I have treated every list once i create it.
Leetcode still claims time exceeded
this is part their input (it's double or triple this length)
[1,1,0,1,0,1,0,0,0,0,0,0,0,0,1,0,0,1,0,0,1,1,1,0,1,1,1,1,1,1,1,1,0,1,0,0,1,0,0,1,1,1,1,0,0,1,0,0,0,1,1,1,1,0,0,0,1,0,0,0,0,1,0,0,1,0,1,1,1,0,0,0,1,1,0,0,1,1,0,1,0,0,0,0,0,0,0,1,0,0,1,1,0,1,0,1,1,1,1,0,1,1,0,0,0,1,1,0,0,1,1,1,1,0,0,0,1,1,1,0,1,1,0,1,0,0,1,0,1,1,1,0,0,1,0,1,1,0,0,0,1,1,0,0,1,0,1,1,1,1,1,1,0,1,0,0,1,0,0,1,1,1,1,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,0,0,1,1,1,1,
Appreciate help with optimizing these:
class Solution(object):
#version 2
def findMaxLength2( nums):
"""
:type nums: List[int]
:rtype: int
"""
l_sub = [] #list of subarray derived from nums
LEN = len(nums)
_max = 0
len_max = 0
# divides into subarrays
for i in range(LEN):
count = [0] * 2
for j in range(i + 1, LEN + 1):
_str = "".join([str(_m) for _m in nums[i:j]])
count[0]= _str.count("0")
count[1] = _str.count ("1")
if count[0] == count[1] and count[1] >= _max :
_max = count[0]
len_max = _max * 2
return len_max
#version 3:
def findMaxLength3( nums):
"""
:type nums: List[int]
:rtype: int
"""
l_sub = [] #list of subarray derived from nums
LEN = len(nums)
_max = 0
len_max = 0
# divides into subarrays
for i in range(LEN):
for j in range(i + 1, LEN + 1):
ones = sum(filter(lambda x:x ==1 , nums[i:j]))
zeros= len (nums[i:j]) - ones
if ones == zeros and zeros >= _max :
_max = zeros
len_max = _max * 2
return len_max
.count
works on lists of integers, asnums[i:j].count(0)
. Better than that issum(nums[i:j]) - (j-i)
, but even better is the incremental scheme described by Cincinnatus.