inputs
stringlengths 50
14k
| targets
stringlengths 4
655k
|
|---|---|
In a country popular for train travel, you have planned some train travelling one year in advance. The days of the year that you will travel is given as an array days. Each day is an integer from 1 to 365.
Train tickets are sold in 3 different ways:
a 1-day pass is sold for costs[0] dollars;
a 7-day pass is sold for costs[1] dollars;
a 30-day pass is sold for costs[2] dollars.
The passes allow that many days of consecutive travel. For example, if we get a 7-day pass on day 2, then we can travel for 7 days: day 2, 3, 4, 5, 6, 7, and 8.
Return the minimum number of dollars you need to travel every day in the given list of days.
Example 1:
Input: days = [1,4,6,7,8,20], costs = [2,7,15]
Output: 11
Explanation:
For example, here is one way to buy passes that lets you travel your travel plan:
On day 1, you bought a 1-day pass for costs[0] = $2, which covered day 1.
On day 3, you bought a 7-day pass for costs[1] = $7, which covered days 3, 4, ..., 9.
On day 20, you bought a 1-day pass for costs[0] = $2, which covered day 20.
In total you spent $11 and covered all the days of your travel.
Example 2:
Input: days = [1,2,3,4,5,6,7,8,9,10,30,31], costs = [2,7,15]
Output: 17
Explanation:
For example, here is one way to buy passes that lets you travel your travel plan:
On day 1, you bought a 30-day pass for costs[2] = $15 which covered days 1, 2, ..., 30.
On day 31, you bought a 1-day pass for costs[0] = $2 which covered day 31.
In total you spent $17 and covered all the days of your travel.
Note:
1 <= days.length <= 365
1 <= days[i] <= 365
days is in strictly increasing order.
costs.length == 3
1 <= costs[i] <= 1000
|
class Solution:
def mincostTickets(self, days: List[int], costs: List[int]) -> int:
if not days:
return 0
dp = {}
def getMin(idx, valid_count_past):
if idx == len(days):
return 0
if days[idx] <= valid_count_past:
return getMin(idx+1, valid_count_past)
if idx in dp:
return dp[idx]
m1 = costs[0] + getMin(idx+1, days[idx])
m7 = costs[1] + getMin(idx+1, days[idx]+6)
m30 = costs[2] + getMin(idx+1, days[idx]+29)
dp[idx] = min(m1,m7,m30)
return dp[idx]
return getMin(0,0)
|
You are given a string containing only 4 kinds of characters 'Q', 'W', 'E' and 'R'.
A string is said to be balanced if each of its characters appears n/4 times where n is the length of the string.
Return the minimum length of the substring that can be replaced with any other string of the same length to make the original string s balanced.
Return 0 if the string is already balanced.
Example 1:
Input: s = "QWER"
Output: 0
Explanation: s is already balanced.
Example 2:
Input: s = "QQWE"
Output: 1
Explanation: We need to replace a 'Q' to 'R', so that "RQWE" (or "QRWE") is balanced.
Example 3:
Input: s = "QQQW"
Output: 2
Explanation: We can replace the first "QQ" to "ER".
Example 4:
Input: s = "QQQQ"
Output: 3
Explanation: We can replace the last 3 'Q' to make s = "QWER".
Constraints:
1 <= s.length <= 10^5
s.length is a multiple of 4
s contains only 'Q', 'W', 'E' and 'R'.
|
class Solution:
def balancedString(self, s: str) -> int:
# minimum window so that outside is possible
if len(s) //4 != len(s) / 4: return -1
ans, lb, n_cnt = len(s), 0, collections.Counter(s)
i = 0
while i < len(s):
n_cnt[s[i]] -= 1
while lb < len(s) and all(len(s) / 4 >= n_cnt[c] for c in 'QWER'):
ans = min(ans, abs(i - lb + 1))
if ans == 0: return 0
n_cnt[s[lb]] += 1
lb += 1
# here is actually a swap?
if lb > i:
i, lb = lb, i
i +=1
return ans
|
You are given a string containing only 4 kinds of characters 'Q', 'W', 'E' and 'R'.
A string is said to be balanced if each of its characters appears n/4 times where n is the length of the string.
Return the minimum length of the substring that can be replaced with any other string of the same length to make the original string s balanced.
Return 0 if the string is already balanced.
Example 1:
Input: s = "QWER"
Output: 0
Explanation: s is already balanced.
Example 2:
Input: s = "QQWE"
Output: 1
Explanation: We need to replace a 'Q' to 'R', so that "RQWE" (or "QRWE") is balanced.
Example 3:
Input: s = "QQQW"
Output: 2
Explanation: We can replace the first "QQ" to "ER".
Example 4:
Input: s = "QQQQ"
Output: 3
Explanation: We can replace the last 3 'Q' to make s = "QWER".
Constraints:
1 <= s.length <= 10^5
s.length is a multiple of 4
s contains only 'Q', 'W', 'E' and 'R'.
|
class Solution:
def balancedString(self, s: str) -> int:
# minimum window so that outside is possible
if len(s) //4 != len(s) / 4: return -1
ans, p1, p2, n_cnt = len(s), 0, 0, collections.Counter(s)
while p1 < len(s):
n_cnt[s[p1]] -= 1
while p2 < len(s) and all(len(s) / 4 >= n_cnt[c] for c in 'QWER'):
ans = min(ans, abs(p1 - p2 + 1))
n_cnt[s[p2]] += 1
p2 += 1
# here is actually a swap?
if p2 > p1:
p1, p2 = p2, p1
p1 +=1
return ans
|
You are given a string containing only 4 kinds of characters 'Q', 'W', 'E' and 'R'.
A string is said to be balanced if each of its characters appears n/4 times where n is the length of the string.
Return the minimum length of the substring that can be replaced with any other string of the same length to make the original string s balanced.
Return 0 if the string is already balanced.
Example 1:
Input: s = "QWER"
Output: 0
Explanation: s is already balanced.
Example 2:
Input: s = "QQWE"
Output: 1
Explanation: We need to replace a 'Q' to 'R', so that "RQWE" (or "QRWE") is balanced.
Example 3:
Input: s = "QQQW"
Output: 2
Explanation: We can replace the first "QQ" to "ER".
Example 4:
Input: s = "QQQQ"
Output: 3
Explanation: We can replace the last 3 'Q' to make s = "QWER".
Constraints:
1 <= s.length <= 10^5
s.length is a multiple of 4
s contains only 'Q', 'W', 'E' and 'R'.
|
class Solution:
def balancedString(self, s: str) -> int:
# minimum window so that outside is possible
if len(s) //4 != len(s) / 4: return -1
ans, p1, p2, n_cnt = len(s), 0, 0, collections.Counter(s)
while p1 < len(s):
n_cnt[s[p1]] -= 1
while p2 < len(s) and all(len(s) / 4 >= n_cnt[c] for c in 'QWER'):
ans = min(ans, abs(p1 - p2 + 1))
n_cnt[s[p2]] += 1
p2 += 1
if p2 > p1:
p1, p2 = p2, p1
p1 +=1
return ans
|
You are given a string containing only 4 kinds of characters 'Q', 'W', 'E' and 'R'.
A string is said to be balanced if each of its characters appears n/4 times where n is the length of the string.
Return the minimum length of the substring that can be replaced with any other string of the same length to make the original string s balanced.
Return 0 if the string is already balanced.
Example 1:
Input: s = "QWER"
Output: 0
Explanation: s is already balanced.
Example 2:
Input: s = "QQWE"
Output: 1
Explanation: We need to replace a 'Q' to 'R', so that "RQWE" (or "QRWE") is balanced.
Example 3:
Input: s = "QQQW"
Output: 2
Explanation: We can replace the first "QQ" to "ER".
Example 4:
Input: s = "QQQQ"
Output: 3
Explanation: We can replace the last 3 'Q' to make s = "QWER".
Constraints:
1 <= s.length <= 10^5
s.length is a multiple of 4
s contains only 'Q', 'W', 'E' and 'R'.
|
class Solution:
def balancedString(self, s: str) -> int:
# minimum window so that outside is possible
if len(s) //4 != len(s) / 4: return -1
ans, p1, p2, n_cnt = len(s), 0, 0, collections.Counter(s)
while p1 < len(s):
n_cnt[s[p1]] -= 1
while p2 < len(s) and all(len(s) / 4 >= n_cnt[c] for c in 'QWER'):
ans = min(ans, abs(p1 - p2 + 1))
n_cnt[s[p2]] += 1
p2 += 1
if p2 > p1:
p1, p2 = p2, p1
p1 +=1
return ans
def balancedString(self, s: str) -> int:
# minimum window so that outside is possible
if len(s) //4 != len(s) / 4: return -1
ans, p1, p2, n_cnt = len(s), 0, 0, collections.Counter(s)
while p1 < len(s):
n_cnt[s[p1]] -= 1
while p2 < min(p1+2, len(s)) and all(len(s) / 4 >= n_cnt[c] for c in 'QWER'):
# can go beyond one position
ans = min(ans, abs(p1 - p2 + 1))
n_cnt[s[p2]] += 1
p2 += 1
# if p2 > p1:
# p1, p2 = p2, p1
p1 +=1
return ans
|
You are given a string containing only 4 kinds of characters 'Q', 'W', 'E' and 'R'.
A string is said to be balanced if each of its characters appears n/4 times where n is the length of the string.
Return the minimum length of the substring that can be replaced with any other string of the same length to make the original string s balanced.
Return 0 if the string is already balanced.
Example 1:
Input: s = "QWER"
Output: 0
Explanation: s is already balanced.
Example 2:
Input: s = "QQWE"
Output: 1
Explanation: We need to replace a 'Q' to 'R', so that "RQWE" (or "QRWE") is balanced.
Example 3:
Input: s = "QQQW"
Output: 2
Explanation: We can replace the first "QQ" to "ER".
Example 4:
Input: s = "QQQQ"
Output: 3
Explanation: We can replace the last 3 'Q' to make s = "QWER".
Constraints:
1 <= s.length <= 10^5
s.length is a multiple of 4
s contains only 'Q', 'W', 'E' and 'R'.
|
class Solution:
def balancedString(self, s: str) -> int:
# minimum window so that outside is possible
if len(s) //4 != len(s) / 4: return -1
ans, p1, p2, n_cnt = len(s), 0, 0, collections.Counter(s)
while p1 < len(s):
n_cnt[s[p1]] -= 1
while p2 < len(s) and all(len(s) / 4 >= n_cnt[c] for c in 'QWER'):
ans = min(ans, abs(p1 - p2 + 1))
n_cnt[s[p2]] += 1
p2 += 1
if p2 > p1:
p1, p2 = p2, p1
p1 +=1
return ans
def balancedString(self, s: str) -> int:
# minimum window so that outside is possible
if len(s) //4 != len(s) / 4: return -1
ans, p1, p2, n_cnt = len(s), 0, 0, collections.Counter(s)
while p1 < len(s):
n_cnt[s[p1]] -= 1
while p2 < min(p1+2, len(s)) and all(len(s) / 4 >= n_cnt[c] for c in 'QWER'):
ans = min(ans, abs(p1 - p2 + 1))
n_cnt[s[p2]] += 1
p2 += 1
# if p2 > p1:
# p1, p2 = p2, p1
p1 +=1
return ans
|
You are given a string containing only 4 kinds of characters 'Q', 'W', 'E' and 'R'.
A string is said to be balanced if each of its characters appears n/4 times where n is the length of the string.
Return the minimum length of the substring that can be replaced with any other string of the same length to make the original string s balanced.
Return 0 if the string is already balanced.
Example 1:
Input: s = "QWER"
Output: 0
Explanation: s is already balanced.
Example 2:
Input: s = "QQWE"
Output: 1
Explanation: We need to replace a 'Q' to 'R', so that "RQWE" (or "QRWE") is balanced.
Example 3:
Input: s = "QQQW"
Output: 2
Explanation: We can replace the first "QQ" to "ER".
Example 4:
Input: s = "QQQQ"
Output: 3
Explanation: We can replace the last 3 'Q' to make s = "QWER".
Constraints:
1 <= s.length <= 10^5
s.length is a multiple of 4
s contains only 'Q', 'W', 'E' and 'R'.
|
from sys import maxsize
from collections import Counter
class Solution:
def balancedString(self, s):
n = len(s)
right = 0
chars = Counter(s)
res = maxsize
for left in range(n):
while right <= n - 1 and any(chars[c] > n // 4 for c in 'QWER'):
chars[s[right]] -= 1
right += 1
if all(chars[c] <= n // 4 for c in 'QWER'):
res = min(res, right - left)
chars[s[left]] += 1
return res
|
You are given a string containing only 4 kinds of characters 'Q', 'W', 'E' and 'R'.
A string is said to be balanced if each of its characters appears n/4 times where n is the length of the string.
Return the minimum length of the substring that can be replaced with any other string of the same length to make the original string s balanced.
Return 0 if the string is already balanced.
Example 1:
Input: s = "QWER"
Output: 0
Explanation: s is already balanced.
Example 2:
Input: s = "QQWE"
Output: 1
Explanation: We need to replace a 'Q' to 'R', so that "RQWE" (or "QRWE") is balanced.
Example 3:
Input: s = "QQQW"
Output: 2
Explanation: We can replace the first "QQ" to "ER".
Example 4:
Input: s = "QQQQ"
Output: 3
Explanation: We can replace the last 3 'Q' to make s = "QWER".
Constraints:
1 <= s.length <= 10^5
s.length is a multiple of 4
s contains only 'Q', 'W', 'E' and 'R'.
|
class Solution:
def balancedString(self, s: str) -> int:
# minimum window so that outside is possible
if len(s) //4 != len(s) / 4: return -1
ans, lb, n_cnt = len(s), 0, collections.Counter(s)
for i, l in enumerate(s):
n_cnt[l] -= 1
while lb < len(s) and all(len(s) / 4 >= n_cnt[c] for c in 'QWER'):
# how to shrink?
ans = min(ans, i - lb + 1)
n_cnt[s[lb]] += 1
lb += 1
return ans
|
Given a positive integer N, return the number of positive integers less than or equal to N that have at least 1 repeated digit.
Example 1:
Input: 20
Output: 1
Explanation: The only positive number (<= 20) with at least 1 repeated digit is 11.
Example 2:
Input: 100
Output: 10
Explanation: The positive numbers (<= 100) with atleast 1 repeated digit are 11, 22, 33, 44, 55, 66, 77, 88, 99, and 100.
Example 3:
Input: 1000
Output: 262
Note:
1 <= N <= 10^9
|
class Solution:
def numDupDigitsAtMostN(self, N: int) -> int:
# N -> total numbers less than or equal to N
# We will calculate the integers with all different digits (which are less than/equal to N)
# Then the answer would be: N - nums_with_different_digits
# Calculate the number of digits in N
NN, dd = N, 0
nums = [] # store the digits
while(NN):
dd += 1
nums.append(NN % 10)
NN //= 10
nums.reverse()
# numbers with less digits than that of N
numbers = 0
for i in range(dd-1):
numbers += 9 * (math.factorial(9) // math.factorial(9-i))
# find the N-digit numbers (all-different)
already_visited_digits = set()
def fac2(n, k):
return math.factorial(n) // math.factorial(n-k)
for i,n in enumerate(nums):
k = 0
for j in range((1 if i==0 else 0), (n+1 if i==dd-1 else n)):
if(j in already_visited_digits):
continue
k += 1
numbers += k * fac2(10-i-1, dd-i-1)
if n in already_visited_digits:
# All the numbers with this prefix will have at least one common digit
break
already_visited_digits.add(n)
return N - numbers
|
Given a positive integer N, return the number of positive integers less than or equal to N that have at least 1 repeated digit.
Example 1:
Input: 20
Output: 1
Explanation: The only positive number (<= 20) with at least 1 repeated digit is 11.
Example 2:
Input: 100
Output: 10
Explanation: The positive numbers (<= 100) with atleast 1 repeated digit are 11, 22, 33, 44, 55, 66, 77, 88, 99, and 100.
Example 3:
Input: 1000
Output: 262
Note:
1 <= N <= 10^9
|
class Solution:
def numDupDigitsAtMostN(self, N: int) -> int:
## https://leetcode.com/problems/numbers-with-repeated-digits/discuss/256725/JavaPython-Count-the-Number-Without-Repeated-Digit
# \"\"\"
# The corner case is too hard to manage...
# count res as N - total number without duplicated digits.
# turns into a math and permutation problem.
# select m out of n
# P(m, n): n! / (n-m)!
# Algorithm:
# lets say N has k digits.
# 1) count number less than k digits
# lets say number with i digits
# first digit 1 ~ 9, following option is 0 ~ 9 without first digit
# count = 9 * P(i-1,9)
# 2) count number has k digits.
# Calculate digits with same prefix.
# Prefix cannot has duplicate digits.
# for case like 77xxx, we should stop the calculation.
# \"\"\"
def numPerm(n, r):
return math.factorial(n)//math.factorial(n-r)
# N + 1 as padding.
nums = [int(d) for d in str(N + 1)]
K = len(nums) # N has K digits
cnt = 0 # number with no repeated val
# count **postive number with digits less than K
for i in range(1, K):
cnt += 9*numPerm(9, i-1)
# count number with K digits
seen = set() # seen digit
for i in range(K):
# prefix = nums[:i] + currentDigit
# currentDigit < nums[i]
for x in range(1 if i == 0 else 0, nums[i]):
if x in seen: continue # avoid duplication
# cnt += P(K - (i + 1), 10 - (i + 1))
cnt += numPerm(10 - (i + 1), K - (i + 1))
# since next iteration, prefix has duplicate digits, break
if nums[i] in seen: break
seen.add(nums[i])
return N - cnt
|
Given a positive integer N, return the number of positive integers less than or equal to N that have at least 1 repeated digit.
Example 1:
Input: 20
Output: 1
Explanation: The only positive number (<= 20) with at least 1 repeated digit is 11.
Example 2:
Input: 100
Output: 10
Explanation: The positive numbers (<= 100) with atleast 1 repeated digit are 11, 22, 33, 44, 55, 66, 77, 88, 99, and 100.
Example 3:
Input: 1000
Output: 262
Note:
1 <= N <= 10^9
|
class Solution:
def numDupDigitsAtMostN(self, N: int) -> int:
k = 0
num = []
t = N
while t:
num.append(t%10)
t = t//10
k += 1
num = num[::-1]
digits = [i for i in range(10)]
dp = [[0 for _ in range(2)] for _ in range(k+1)]
def count(dp, dig, state, d1, seen):
if dig == k:
return 1
if dp[dig][state]:
return dp[dig][state]
seen.add(d1)
for d in digits:
if d in seen:
continue
if state == 0:
dp[dig][state] += count(dp, dig + 1, state, d, seen)
elif state == 1:
if d > num[dig]:
continue
if d < num[dig]:
dp[dig][state] += count(dp, dig + 1, state^1, d, seen)
elif d == num[dig]:
dp[dig][state] += count(dp, dig + 1, state, d, seen)
seen.remove(d1)
return dp[dig][state]
v = 0
# print(k)
for d in range(1, 10):
seen = set()
if d < num[0]:
v += count(dp, 1, 0, d, seen)
elif d == num[0]:
v += count(dp, 1, 1, d, seen)
for i in range(1, k):
for p in range(1, 10):
seen = set()
dp = [[0 for _ in range(2)] for _ in range(k+1)]
v += count(dp, i + 1, 0, p, seen)
# print(v)
# print(dp[3][0])
return N - v
|
Given a positive integer N, return the number of positive integers less than or equal to N that have at least 1 repeated digit.
Example 1:
Input: 20
Output: 1
Explanation: The only positive number (<= 20) with at least 1 repeated digit is 11.
Example 2:
Input: 100
Output: 10
Explanation: The positive numbers (<= 100) with atleast 1 repeated digit are 11, 22, 33, 44, 55, 66, 77, 88, 99, and 100.
Example 3:
Input: 1000
Output: 262
Note:
1 <= N <= 10^9
|
class Solution:
def numDupDigitsAtMostN(self, N: int) -> int:
# https://leetcode.com/problems/numbers-with-repeated-digits/discuss/592922/Python-Well-commented-solution-with-easy-to-follow-recursion
memo = {}
def f(digits_of_N, i, digits_used, any_digit):
if i == k:
return 1
key = (i, digits_used, any_digit)
if key in memo:
return memo[key]
cnt = 0
min_digit = 1 if i == 0 else 0
max_digit = 9 if any_digit else digits_of_N[i]
for d in range(min_digit, max_digit + 1):
if digits_used & (1 << d) != 0:
continue
cnt += f(digits_of_N, i + 1, digits_used | (1 << d), any_digit or (d < digits_of_N[i]))
memo[key] = cnt
return cnt
if N <= 9:
return 0
k = len(str(N))
cnt = 0
for i in range(1, k):
all_possible_ints = 9 * 10**(i-1)
ints_with_unique_digits = 9
nb_choices = 9
for j in range(1, i):
ints_with_unique_digits *= nb_choices
nb_choices -= 1
cnt += all_possible_ints - ints_with_unique_digits
all_ints_with_k_digits = N - int('9'*(k-1))
digits_of_N = [int(d) for d in str(N)]
ints_with_unique_k_digits = f(digits_of_N, 0, 0, False)
cnt += all_ints_with_k_digits - ints_with_unique_k_digits
return cnt
|
Given a positive integer N, return the number of positive integers less than or equal to N that have at least 1 repeated digit.
Example 1:
Input: 20
Output: 1
Explanation: The only positive number (<= 20) with at least 1 repeated digit is 11.
Example 2:
Input: 100
Output: 10
Explanation: The positive numbers (<= 100) with atleast 1 repeated digit are 11, 22, 33, 44, 55, 66, 77, 88, 99, and 100.
Example 3:
Input: 1000
Output: 262
Note:
1 <= N <= 10^9
|
def f(n,s,e,ci,di,v):
if n==ci:
return 1
a=0
if (e,ci,v) in di:
return di[e,ci,v]
for i in range(10):
if e==0:
if not v>>i&1:
eee=v|(1<<i)
a+=f(n,s,0,ci+1,di,eee)
else:
if i>int(s[ci]):
break
if int(s[ci])==i:
if not v>>i&1:
eee=v|(1<<i)
a+=f(n,s,1,ci+1,di,eee)
break
if not v>>i&1:
eee=v|(1<<i)
a+=f(n,s,0,ci+1,di,eee)
di[e,ci,v]=a
return a
class Solution:
def numDupDigitsAtMostN(self, n: int) -> int:
if n<=10:
return 0
s=str(n)
l=len(s)
ans=10
prev=9
for i in range(9,9-l+2,-1):
ans+= prev*i
prev=prev*i
a=0
di={}
v=0
for i in range(1,10):
if i>int(s[0]):
break
if i==int(s[0]):
e=1<<i
a+=f(l,s,1,1,di,e)
break
e=1<<i
a+=f(l,s,0,1,di,e)
return n-a-ans+1
|
Given a positive integer N, return the number of positive integers less than or equal to N that have at least 1 repeated digit.
Example 1:
Input: 20
Output: 1
Explanation: The only positive number (<= 20) with at least 1 repeated digit is 11.
Example 2:
Input: 100
Output: 10
Explanation: The positive numbers (<= 100) with atleast 1 repeated digit are 11, 22, 33, 44, 55, 66, 77, 88, 99, and 100.
Example 3:
Input: 1000
Output: 262
Note:
1 <= N <= 10^9
|
class Solution:
def numDupDigitsAtMostN(self, N: int) -> int:
digits = []
M=N+1
while M>0:
digits.append(M%10)
M//=10
part_1 = 0
prod=9
i_1=9
n = len(digits)
for i in range(n-1):
part_1+=prod
# print(i,part_1,prod)
if i_1>1:
if i>0:
i_1-=1
prod*=i_1
i_1=9
seen = set([])
cols = [0 for i in range(10)]
while len(digits)>0:
digit = digits.pop()
if len(digits)==n-1:
prod = digit-1
else:
prod = digit-cols[digit]
j_1=i_1
for i in range(len(digits)):
prod*=j_1
j_1-=1
i_1-=1
part_1+=prod
if digit in seen:
break
else:
seen.add(digit)
for i in range(digit+1,10):
cols[i]+=1
return N -part_1
|
Given a positive integer N, return the number of positive integers less than or equal to N that have at least 1 repeated digit.
Example 1:
Input: 20
Output: 1
Explanation: The only positive number (<= 20) with at least 1 repeated digit is 11.
Example 2:
Input: 100
Output: 10
Explanation: The positive numbers (<= 100) with atleast 1 repeated digit are 11, 22, 33, 44, 55, 66, 77, 88, 99, and 100.
Example 3:
Input: 1000
Output: 262
Note:
1 <= N <= 10^9
|
def f(n,s,e,ci,di,v):
if n==ci:
return 1
a=0
if (e,ci,v) in di:
return di[e,ci,v]
for i in range(10):
if e==0:
if not v>>i&1:
eee=v|(1<<i)
a+=f(n,s,0,ci+1,di,eee)
else:
if i>int(s[ci]):
break
if int(s[ci])==i:
if not v>>i&1:
eee=v|(1<<i)
a+=f(n,s,1,ci+1,di,eee)
break
if not v>>i&1:
eee=v|(1<<i)
a+=f(n,s,0,ci+1,di,eee)
di[e,ci,v]=a
return a
class Solution:
def numDupDigitsAtMostN(self, n: int) -> int:
if n<=10:
return 0
s=str(n)
l=len(s)
ans=10
prev=9
for i in range(9,9-l+2,-1):
ans+= prev*i
prev=prev*i
a=0
di={}
v=0
for i in range(1,10):
if i>int(s[0]):
break
if i==int(s[0]):
e=1<<i
a+=f(l,s,1,1,di,e)
break
e=1<<i
a+=f(l,s,0,1,di,e)
return n-a-ans+1
|
Given a positive integer N, return the number of positive integers less than or equal to N that have at least 1 repeated digit.
Example 1:
Input: 20
Output: 1
Explanation: The only positive number (<= 20) with at least 1 repeated digit is 11.
Example 2:
Input: 100
Output: 10
Explanation: The positive numbers (<= 100) with atleast 1 repeated digit are 11, 22, 33, 44, 55, 66, 77, 88, 99, and 100.
Example 3:
Input: 1000
Output: 262
Note:
1 <= N <= 10^9
|
class Solution:
def numDupDigitsAtMostN(self, N: int) -> int:
N = str(N)
@lru_cache(None)
def dfs(i, r, m):
if i == len(N):
return 1
ans = 0
limit = int(N[i]) if r else 9
for k in range(0,limit+1):
if m & (1 << k) == 0:
mask = m | (1 << k) if m or k > 0 else 0
if k < limit or not r:
ans += dfs(i+1, False, mask)
else:
ans += dfs(i+1, True, mask)
return ans
return int(N) - dfs(0, True, 0) + 1
|
Given a positive integer N, return the number of positive integers less than or equal to N that have at least 1 repeated digit.
Example 1:
Input: 20
Output: 1
Explanation: The only positive number (<= 20) with at least 1 repeated digit is 11.
Example 2:
Input: 100
Output: 10
Explanation: The positive numbers (<= 100) with atleast 1 repeated digit are 11, 22, 33, 44, 55, 66, 77, 88, 99, and 100.
Example 3:
Input: 1000
Output: 262
Note:
1 <= N <= 10^9
|
from functools import lru_cache
class Solution:
def numDupDigitsAtMostN(self, N: int) -> int:
@lru_cache(None)
def dfs(state, x, lz=False):
n = len(str(x))
if x < 10:
res = 0
if not lz:
for i in range(1, x + 1):
if state & (1 << i) == 0:
res += 1
else:
for i in range(x + 1):
if state & (1 << i) == 0:
res += 1
# print(bin(state), x, lz, res)
return res
if not lz:
res = dfs(state, 10 ** (n - 1) - 1)
else:
if state & 1 == 0:
res = dfs(state | 1, 10 ** (n - 1) - 1, True)
else:
res = 0
for i in range(1, int(str(x)[0])):
if state & (1 << i) == 0:
res += dfs(state | (1 << i), 10 ** (n - 1) - 1, True)
if state & (1 << int(str(x)[0])) == 0:
if not (x % 10 ** (n - 1) == 0 and n >= 3):
if x % 10 ** (n - 1) >= 10 ** (n - 2) or n <= 2:
res += dfs(state | (1 << int(str(x)[0])), x % 10 ** (n - 1), True)
elif n >= 3 and 1 & state == 0 and x % 10 ** (n - 1) >= 10 ** (n - 3):
res += dfs(state | (1 << int(str(x)[0])) + 1, x % 10 ** (n - 1), True)
# print(bin(state), x, lz, res)
return res
return N - dfs(0, N)
|
Given a positive integer N, return the number of positive integers less than or equal to N that have at least 1 repeated digit.
Example 1:
Input: 20
Output: 1
Explanation: The only positive number (<= 20) with at least 1 repeated digit is 11.
Example 2:
Input: 100
Output: 10
Explanation: The positive numbers (<= 100) with atleast 1 repeated digit are 11, 22, 33, 44, 55, 66, 77, 88, 99, and 100.
Example 3:
Input: 1000
Output: 262
Note:
1 <= N <= 10^9
|
class Solution:
def numDupDigitsAtMostN(self, n: int) -> int:
s = str(n)
@lru_cache(None)
def dp(i, smaller, nonzero, used):
if i==len(s):
return nonzero
ret = 0
if smaller:
for dig in range(10):
if dig==0 and not nonzero:
ret += dp(i+1, True, False, used)
else:
if (1<<dig)&used:
continue
ret += dp(i+1, True, True, used|(1<<dig))
else:
for dig in range(10):
if dig>int(s[i]):
break
elif dig==int(s[i]):
if (1<<dig)&used:
continue
ret += dp(i+1, False, True, used|(1<<dig))
else:
if dig==0 and not nonzero:
ret += dp(i+1, True, False, used)
else:
if (1<<dig)&used:
continue
ret += dp(i+1, True, True, used|(1<<dig))
# print(i, smaller, nonzero, bin(used), ret)
return ret
# print(dp(0, False, False, 0))
return n - dp(0, False, False, 0)
|
Given a positive integer N, return the number of positive integers less than or equal to N that have at least 1 repeated digit.
Example 1:
Input: 20
Output: 1
Explanation: The only positive number (<= 20) with at least 1 repeated digit is 11.
Example 2:
Input: 100
Output: 10
Explanation: The positive numbers (<= 100) with atleast 1 repeated digit are 11, 22, 33, 44, 55, 66, 77, 88, 99, and 100.
Example 3:
Input: 1000
Output: 262
Note:
1 <= N <= 10^9
|
class Solution:
def numDupDigitsAtMostN(self, N: int) -> int:
L = list(map(int, str(N + 1)))
res, n = 0, len(str(N + 1))
def A(m, n):
return 1 if n == 0 else A(m, n - 1) * (m - n + 1)
for i in range(1, n): res += 9 * A(9, i - 1)
s = set()
for i, x in enumerate(L):
for y in range(0 if i else 1, x):
if y not in s:
res += A(9 - i, n - i - 1)
if x in s: break
s.add(x)
return N - res
|
Given a positive integer N, return the number of positive integers less than or equal to N that have at least 1 repeated digit.
Example 1:
Input: 20
Output: 1
Explanation: The only positive number (<= 20) with at least 1 repeated digit is 11.
Example 2:
Input: 100
Output: 10
Explanation: The positive numbers (<= 100) with atleast 1 repeated digit are 11, 22, 33, 44, 55, 66, 77, 88, 99, and 100.
Example 3:
Input: 1000
Output: 262
Note:
1 <= N <= 10^9
|
class Solution:
def numDupDigitsAtMostN(self, N: int) -> int:
list_N = list(map(int, str(N + 1)))
solution = 0
def permutation(m, n):
return 1 if n == 0 else permutation(m, n - 1) * (m - n + 1)
for i in range(1, len(list_N)):
solution += 9 * permutation(9, i - 1)
seen_set = set()
for i, x in enumerate(list_N):
for y in range(0 if i else 1, x):
if y not in seen_set:
solution += permutation(9 - i, len(list_N) - i - 1)
if x in seen_set:
break
seen_set.add(x)
return N - solution
|
Given a positive integer N, return the number of positive integers less than or equal to N that have at least 1 repeated digit.
Example 1:
Input: 20
Output: 1
Explanation: The only positive number (<= 20) with at least 1 repeated digit is 11.
Example 2:
Input: 100
Output: 10
Explanation: The positive numbers (<= 100) with atleast 1 repeated digit are 11, 22, 33, 44, 55, 66, 77, 88, 99, and 100.
Example 3:
Input: 1000
Output: 262
Note:
1 <= N <= 10^9
|
class Solution:
def numDupDigitsAtMostN(self, N: int) -> int:
if N < 100:
return N // 11
s = str(N)
l = len(s)
if l > 10:
return N - 8877690
mapping = {
0: 0,
1: 9,
2: 90,
3: 738,
4: 5274,
5: 32490,
6: 168570,
7: 712890,
8: 2345850,
9: 5611770,
10: 8877690}
seen = set()
for i, d in enumerate(s):
d = int(d)
if d > 0:
f = sum(1 for j in range((1 if i == 0 else 0), d) if j not in seen)
for j in range(l-i-1):
f *= (9-i-j)
N -= f
if i == l - 1 and d not in seen:
N -= 1
if d in seen:
break
seen.add(d)
return N - mapping[l-1]
|
Given a positive integer N, return the number of positive integers less than or equal to N that have at least 1 repeated digit.
Example 1:
Input: 20
Output: 1
Explanation: The only positive number (<= 20) with at least 1 repeated digit is 11.
Example 2:
Input: 100
Output: 10
Explanation: The positive numbers (<= 100) with atleast 1 repeated digit are 11, 22, 33, 44, 55, 66, 77, 88, 99, and 100.
Example 3:
Input: 1000
Output: 262
Note:
1 <= N <= 10^9
|
class Solution:
def numDupDigitsAtMostN(self, N: int) -> int:
digits = list(map(int, str(N)))
n = len(digits)
d = 0
for i in range(1, n):
d += 9 * math.factorial(9) // math.factorial(10 - i)
for i, j in enumerate(digits):
for k in range(1 if i == 0 else 0, j):
if k in digits[:i]:
continue
x = 10 - i - 1
d += math.factorial(x) // math.factorial(x - (n - i - 1))
if j in digits[:i]:
break
else:
if i == n - 1:
d += 1
return N - d
|
Given a positive integer N, return the number of positive integers less than or equal to N that have at least 1 repeated digit.
Example 1:
Input: 20
Output: 1
Explanation: The only positive number (<= 20) with at least 1 repeated digit is 11.
Example 2:
Input: 100
Output: 10
Explanation: The positive numbers (<= 100) with atleast 1 repeated digit are 11, 22, 33, 44, 55, 66, 77, 88, 99, and 100.
Example 3:
Input: 1000
Output: 262
Note:
1 <= N <= 10^9
|
class Solution:
def numDupDigitsAtMostN(self, N: int) -> int:
# N -> total numbers less than or equal to N
# We will calculate the integers with all different digits (which are less than/equal to N)
# Then the answer would be: N - nums_with_different_digits
# Calculate the number of digits in N
NN, dd = N, 0
nums = [] # store the digits
while(NN):
dd += 1
nums.append(NN % 10)
NN //= 10
nums.reverse()
# numbers with less digits than that of N
numbers = 0
for i in range(dd-1):
numbers += 9 * (math.factorial(9) // math.factorial(9-i))
# find the N-digit numbers (all-different)
already_visited_digits = set()
def fac2(n, k):
return math.factorial(n) // math.factorial(n-k)
for i,n in enumerate(nums):
k = 0
for j in range((1 if i==0 else 0), (n+1 if i==dd-1 else n)):
if(j in already_visited_digits):
continue
k += 1
numbers += k * fac2(10-i-1, dd-i-1)
if n in already_visited_digits:
# All the numbers with this prefix will have at least one common digit
break
already_visited_digits.add(n)
return N - numbers
|
Given a positive integer N, return the number of positive integers less than or equal to N that have at least 1 repeated digit.
Example 1:
Input: 20
Output: 1
Explanation: The only positive number (<= 20) with at least 1 repeated digit is 11.
Example 2:
Input: 100
Output: 10
Explanation: The positive numbers (<= 100) with atleast 1 repeated digit are 11, 22, 33, 44, 55, 66, 77, 88, 99, and 100.
Example 3:
Input: 1000
Output: 262
Note:
1 <= N <= 10^9
|
def parcfact(m):
return sum([fact(m1) for m1 in range(1,m)])
def fact(m):
p = 1;
for ii in range(m):
p = p*min(9,10-ii)
return p
class Solution:
def numDupDigitsAtMostN(self, N: int) -> int:
found = {}
NS = str(N)
res = parcfact(len(NS))
found = {}
def count(par):
# print(par,len(par),NS)
res = 0
if len(par)==len(NS) and par<=NS:
return 1
elif len(par)<len(NS):
for ii in range(10):
if par.find(str(ii))<0 and par+str(ii)<=NS[:len(par)+1]:
if par+str(ii)<NS[:len(par)+1]:
if not(len(par)) in found:
found[len(par)] = count(par+str(ii))
res = res+found[len(par)]
else:
res = res+count(par+str(ii))
return res
for ii in range(1,int(NS[0])+1):
res = res+count(str(ii))
# print(res,print(found))
return(N-res)
|
Given two sequences pushed and popped with distinct values, return true if and only if this could have been the result of a sequence of push and pop operations on an initially empty stack.
Example 1:
Input: pushed = [1,2,3,4,5], popped = [4,5,3,2,1]
Output: true
Explanation: We might do the following sequence:
push(1), push(2), push(3), push(4), pop() -> 4,
push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1
Example 2:
Input: pushed = [1,2,3,4,5], popped = [4,3,5,1,2]
Output: false
Explanation: 1 cannot be popped before 2.
Constraints:
0 <= pushed.length == popped.length <= 1000
0 <= pushed[i], popped[i] < 1000
pushed is a permutation of popped.
pushed and popped have distinct values.
|
class Solution:
def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:
j = 0
l = []
for i in pushed:
l.append(i)
while l and (l[-1] == popped[j]):
l.pop()
j += 1
if l:
return False
return True
|
Given two sequences pushed and popped with distinct values, return true if and only if this could have been the result of a sequence of push and pop operations on an initially empty stack.
Example 1:
Input: pushed = [1,2,3,4,5], popped = [4,5,3,2,1]
Output: true
Explanation: We might do the following sequence:
push(1), push(2), push(3), push(4), pop() -> 4,
push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1
Example 2:
Input: pushed = [1,2,3,4,5], popped = [4,3,5,1,2]
Output: false
Explanation: 1 cannot be popped before 2.
Constraints:
0 <= pushed.length == popped.length <= 1000
0 <= pushed[i], popped[i] < 1000
pushed is a permutation of popped.
pushed and popped have distinct values.
|
class Solution:
def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:
if len(pushed) != len(popped):
return False
idx = 0
stack = []
for i in range(len(popped)):
if len(stack) > 0 and stack[-1] == popped[i]:
stack.pop()
else:
while idx < len(pushed) and pushed[idx] != popped[i]:
stack.append(pushed[idx])
idx += 1
idx += 1
return len(stack) == 0
|
Given two sequences pushed and popped with distinct values, return true if and only if this could have been the result of a sequence of push and pop operations on an initially empty stack.
Example 1:
Input: pushed = [1,2,3,4,5], popped = [4,5,3,2,1]
Output: true
Explanation: We might do the following sequence:
push(1), push(2), push(3), push(4), pop() -> 4,
push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1
Example 2:
Input: pushed = [1,2,3,4,5], popped = [4,3,5,1,2]
Output: false
Explanation: 1 cannot be popped before 2.
Constraints:
0 <= pushed.length == popped.length <= 1000
0 <= pushed[i], popped[i] < 1000
pushed is a permutation of popped.
pushed and popped have distinct values.
|
class Solution:
def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:
i = 0
j = 0
demo = []
for j in range(len(popped)):
while popped[j] not in demo and i < len(pushed):
demo.append(pushed[i])
i += 1
if demo[-1] == popped[j]:
demo.pop()
else:
return False
return True
|
Given two sequences pushed and popped with distinct values, return true if and only if this could have been the result of a sequence of push and pop operations on an initially empty stack.
Example 1:
Input: pushed = [1,2,3,4,5], popped = [4,5,3,2,1]
Output: true
Explanation: We might do the following sequence:
push(1), push(2), push(3), push(4), pop() -> 4,
push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1
Example 2:
Input: pushed = [1,2,3,4,5], popped = [4,3,5,1,2]
Output: false
Explanation: 1 cannot be popped before 2.
Constraints:
0 <= pushed.length == popped.length <= 1000
0 <= pushed[i], popped[i] < 1000
pushed is a permutation of popped.
pushed and popped have distinct values.
|
class Solution:
def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:
j = 0
stack = []
for x in pushed:
stack.append(x)
while stack and j < len(popped) and stack[-1] == popped[j]:
print(j, stack)
stack.pop()
j += 1
return j == len(popped)
|
Given two sequences pushed and popped with distinct values, return true if and only if this could have been the result of a sequence of push and pop operations on an initially empty stack.
Example 1:
Input: pushed = [1,2,3,4,5], popped = [4,5,3,2,1]
Output: true
Explanation: We might do the following sequence:
push(1), push(2), push(3), push(4), pop() -> 4,
push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1
Example 2:
Input: pushed = [1,2,3,4,5], popped = [4,3,5,1,2]
Output: false
Explanation: 1 cannot be popped before 2.
Constraints:
0 <= pushed.length == popped.length <= 1000
0 <= pushed[i], popped[i] < 1000
pushed is a permutation of popped.
pushed and popped have distinct values.
|
class Solution:
def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:
l = len(pushed)
i = 0
j = 0
while i < l and j < l:
# print(pushed, popped)
if pushed[i] == popped[j]:
pushed[i] = -1
popped[j] = -1
while i > 0:
if pushed[i] != -1:
break
i -= 1
j += 1
else:
i += 1
i = 0
j = 0
r_pop = popped[::-1]
while i < l and j < l:
if pushed[i] == -1:
i += 1
continue
if r_pop[j] == -1:
j += 1
continue
if pushed[i] != popped[j]:
return False
else:
i += 1
j += 1
return True
|
Given two sequences pushed and popped with distinct values, return true if and only if this could have been the result of a sequence of push and pop operations on an initially empty stack.
Example 1:
Input: pushed = [1,2,3,4,5], popped = [4,5,3,2,1]
Output: true
Explanation: We might do the following sequence:
push(1), push(2), push(3), push(4), pop() -> 4,
push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1
Example 2:
Input: pushed = [1,2,3,4,5], popped = [4,3,5,1,2]
Output: false
Explanation: 1 cannot be popped before 2.
Constraints:
0 <= pushed.length == popped.length <= 1000
0 <= pushed[i], popped[i] < 1000
pushed is a permutation of popped.
pushed and popped have distinct values.
|
class Solution:
def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:
stack = []
n = len(pushed)
i = j = 0
while True:
if not stack or stack[-1] != popped[j]:
if i >= n:
return not stack
stack.append(pushed[i])
i += 1
else:
stack.pop()
j += 1
|
Given two sequences pushed and popped with distinct values, return true if and only if this could have been the result of a sequence of push and pop operations on an initially empty stack.
Example 1:
Input: pushed = [1,2,3,4,5], popped = [4,5,3,2,1]
Output: true
Explanation: We might do the following sequence:
push(1), push(2), push(3), push(4), pop() -> 4,
push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1
Example 2:
Input: pushed = [1,2,3,4,5], popped = [4,3,5,1,2]
Output: false
Explanation: 1 cannot be popped before 2.
Constraints:
0 <= pushed.length == popped.length <= 1000
0 <= pushed[i], popped[i] < 1000
pushed is a permutation of popped.
pushed and popped have distinct values.
|
class Solution:
def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:
l=[]
j=i=0
for i in pushed:
l.append(i)
while l and popped and l[-1]==popped[0]:
l.pop()
popped.pop(0)
return len(popped)==0
|
Given two sequences pushed and popped with distinct values, return true if and only if this could have been the result of a sequence of push and pop operations on an initially empty stack.
Example 1:
Input: pushed = [1,2,3,4,5], popped = [4,5,3,2,1]
Output: true
Explanation: We might do the following sequence:
push(1), push(2), push(3), push(4), pop() -> 4,
push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1
Example 2:
Input: pushed = [1,2,3,4,5], popped = [4,3,5,1,2]
Output: false
Explanation: 1 cannot be popped before 2.
Constraints:
0 <= pushed.length == popped.length <= 1000
0 <= pushed[i], popped[i] < 1000
pushed is a permutation of popped.
pushed and popped have distinct values.
|
class Solution:
def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:
j=0
stack=[]
for x in pushed:
stack.append(x)
while stack and j<len(popped) and stack[-1]==popped[j]:
stack.pop()
j+=1
return j==len(popped)
|
Given two sequences pushed and popped with distinct values, return true if and only if this could have been the result of a sequence of push and pop operations on an initially empty stack.
Example 1:
Input: pushed = [1,2,3,4,5], popped = [4,5,3,2,1]
Output: true
Explanation: We might do the following sequence:
push(1), push(2), push(3), push(4), pop() -> 4,
push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1
Example 2:
Input: pushed = [1,2,3,4,5], popped = [4,3,5,1,2]
Output: false
Explanation: 1 cannot be popped before 2.
Constraints:
0 <= pushed.length == popped.length <= 1000
0 <= pushed[i], popped[i] < 1000
pushed is a permutation of popped.
pushed and popped have distinct values.
|
class Solution:
def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:
i, j, k, n = -1, 0, 0, len(pushed)
while i < n and k < n:
if i >= 0 and pushed[i] == popped[k]:
i -= 1
k += 1
else:
if j >= n:
break
i += 1
pushed[i] = pushed[j]
j += 1
return i == -1 and k == n
|
Given two sequences pushed and popped with distinct values, return true if and only if this could have been the result of a sequence of push and pop operations on an initially empty stack.
Example 1:
Input: pushed = [1,2,3,4,5], popped = [4,5,3,2,1]
Output: true
Explanation: We might do the following sequence:
push(1), push(2), push(3), push(4), pop() -> 4,
push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1
Example 2:
Input: pushed = [1,2,3,4,5], popped = [4,3,5,1,2]
Output: false
Explanation: 1 cannot be popped before 2.
Constraints:
0 <= pushed.length == popped.length <= 1000
0 <= pushed[i], popped[i] < 1000
pushed is a permutation of popped.
pushed and popped have distinct values.
|
class Solution:
def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:
'''
start: 1:27
edge cases:
not poping entire stack (nm, pushed is a permutation of popped)
complexity:
O(n) time, O(1) space seems right
approach:
Let's just build a stack and attempt to pop at each opportunity... Seems simple
Greedy approach, always pop if possible, should work fine due to distinct numbers
'''
stack = []
while len(pushed) or len(popped) or len(stack):
if len(stack) and len(popped) and stack[-1] == popped[0]: # can pop
stack.pop()
popped = popped[1:]
elif len(pushed): # can push
stack.append(pushed[0])
pushed = pushed[1:]
else:
return False
return True
|
Given two sequences pushed and popped with distinct values, return true if and only if this could have been the result of a sequence of push and pop operations on an initially empty stack.
Example 1:
Input: pushed = [1,2,3,4,5], popped = [4,5,3,2,1]
Output: true
Explanation: We might do the following sequence:
push(1), push(2), push(3), push(4), pop() -> 4,
push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1
Example 2:
Input: pushed = [1,2,3,4,5], popped = [4,3,5,1,2]
Output: false
Explanation: 1 cannot be popped before 2.
Constraints:
0 <= pushed.length == popped.length <= 1000
0 <= pushed[i], popped[i] < 1000
pushed is a permutation of popped.
pushed and popped have distinct values.
|
class Solution:
def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:
push = []
i = 0
while popped:
if i < len(pushed):
push += [pushed[i]]
while push and push[-1] == popped[0]:
popped.pop(0)
push.pop()
# print(push)
# print(popped)
if i < len(pushed):
i += 1
else:
return False
return True
|
Given two sequences pushed and popped with distinct values, return true if and only if this could have been the result of a sequence of push and pop operations on an initially empty stack.
Example 1:
Input: pushed = [1,2,3,4,5], popped = [4,5,3,2,1]
Output: true
Explanation: We might do the following sequence:
push(1), push(2), push(3), push(4), pop() -> 4,
push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1
Example 2:
Input: pushed = [1,2,3,4,5], popped = [4,3,5,1,2]
Output: false
Explanation: 1 cannot be popped before 2.
Constraints:
0 <= pushed.length == popped.length <= 1000
0 <= pushed[i], popped[i] < 1000
pushed is a permutation of popped.
pushed and popped have distinct values.
|
class Solution:
def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:
if len(pushed) != len(popped): return False
stack, i = [], 0
for j, n in enumerate(pushed):
stack.append(n)
while len(stack) > 0 and popped[i] == stack[-1]:
stack.pop()
i += 1
return len(stack) == 0
|
Given two sequences pushed and popped with distinct values, return true if and only if this could have been the result of a sequence of push and pop operations on an initially empty stack.
Example 1:
Input: pushed = [1,2,3,4,5], popped = [4,5,3,2,1]
Output: true
Explanation: We might do the following sequence:
push(1), push(2), push(3), push(4), pop() -> 4,
push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1
Example 2:
Input: pushed = [1,2,3,4,5], popped = [4,3,5,1,2]
Output: false
Explanation: 1 cannot be popped before 2.
Constraints:
0 <= pushed.length == popped.length <= 1000
0 <= pushed[i], popped[i] < 1000
pushed is a permutation of popped.
pushed and popped have distinct values.
|
class Solution:
def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:
pushed.reverse()
popped.reverse()
stack = []
while pushed:
value = pushed.pop()
stack.append(value)
while stack and popped and stack[-1] == popped[-1]:
popped.pop()
stack.pop()
#if not pushed and not popped:
# return True
if not stack:
return True
return False
|
Given two sequences pushed and popped with distinct values, return true if and only if this could have been the result of a sequence of push and pop operations on an initially empty stack.
Example 1:
Input: pushed = [1,2,3,4,5], popped = [4,5,3,2,1]
Output: true
Explanation: We might do the following sequence:
push(1), push(2), push(3), push(4), pop() -> 4,
push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1
Example 2:
Input: pushed = [1,2,3,4,5], popped = [4,3,5,1,2]
Output: false
Explanation: 1 cannot be popped before 2.
Constraints:
0 <= pushed.length == popped.length <= 1000
0 <= pushed[i], popped[i] < 1000
pushed is a permutation of popped.
pushed and popped have distinct values.
|
class Solution:
def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:
stack = []
j = 0
for x in pushed:
stack.append(x)
while stack and j < len(popped) and stack[-1] == popped[j]:
stack.pop()
j+=1
return True if j == len(popped) else False
|
Given two sequences pushed and popped with distinct values, return true if and only if this could have been the result of a sequence of push and pop operations on an initially empty stack.
Example 1:
Input: pushed = [1,2,3,4,5], popped = [4,5,3,2,1]
Output: true
Explanation: We might do the following sequence:
push(1), push(2), push(3), push(4), pop() -> 4,
push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1
Example 2:
Input: pushed = [1,2,3,4,5], popped = [4,3,5,1,2]
Output: false
Explanation: 1 cannot be popped before 2.
Constraints:
0 <= pushed.length == popped.length <= 1000
0 <= pushed[i], popped[i] < 1000
pushed is a permutation of popped.
pushed and popped have distinct values.
|
class Solution:
def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:
stack = []
push_index = 0
pop_index = 0
n = len(pushed)
while push_index < n:
while stack and stack[-1] == popped[pop_index]:
stack.pop()
pop_index += 1
stack.append(pushed[push_index])
push_index += 1
while stack and stack[-1] == popped[pop_index]:
stack.pop()
pop_index += 1
return True if not stack else False
|
Given two sequences pushed and popped with distinct values, return true if and only if this could have been the result of a sequence of push and pop operations on an initially empty stack.
Example 1:
Input: pushed = [1,2,3,4,5], popped = [4,5,3,2,1]
Output: true
Explanation: We might do the following sequence:
push(1), push(2), push(3), push(4), pop() -> 4,
push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1
Example 2:
Input: pushed = [1,2,3,4,5], popped = [4,3,5,1,2]
Output: false
Explanation: 1 cannot be popped before 2.
Constraints:
0 <= pushed.length == popped.length <= 1000
0 <= pushed[i], popped[i] < 1000
pushed is a permutation of popped.
pushed and popped have distinct values.
|
class Solution:
def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:
pushed.reverse()
popped.reverse()
stack = []
while pushed:
#value = pushed.pop()
#stack.append(value)
stack.append(pushed.pop())
while stack and popped and stack[-1] == popped[-1]:
popped.pop()
stack.pop()
#if not pushed and not popped:
# return True
if not stack:
return True
return False
|
Given two sequences pushed and popped with distinct values, return true if and only if this could have been the result of a sequence of push and pop operations on an initially empty stack.
Example 1:
Input: pushed = [1,2,3,4,5], popped = [4,5,3,2,1]
Output: true
Explanation: We might do the following sequence:
push(1), push(2), push(3), push(4), pop() -> 4,
push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1
Example 2:
Input: pushed = [1,2,3,4,5], popped = [4,3,5,1,2]
Output: false
Explanation: 1 cannot be popped before 2.
Constraints:
0 <= pushed.length == popped.length <= 1000
0 <= pushed[i], popped[i] < 1000
pushed is a permutation of popped.
pushed and popped have distinct values.
|
class Solution:
def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:
pushed.reverse()
popped.reverse()
stack = []
while pushed:
value = pushed.pop()
stack.append(value)
while stack and popped and stack[-1] == popped[-1]:
popped.pop()
stack.pop()
if not pushed and not popped:
return True
return False
|
Given two sequences pushed and popped with distinct values, return true if and only if this could have been the result of a sequence of push and pop operations on an initially empty stack.
Example 1:
Input: pushed = [1,2,3,4,5], popped = [4,5,3,2,1]
Output: true
Explanation: We might do the following sequence:
push(1), push(2), push(3), push(4), pop() -> 4,
push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1
Example 2:
Input: pushed = [1,2,3,4,5], popped = [4,3,5,1,2]
Output: false
Explanation: 1 cannot be popped before 2.
Constraints:
0 <= pushed.length == popped.length <= 1000
0 <= pushed[i], popped[i] < 1000
pushed is a permutation of popped.
pushed and popped have distinct values.
|
class Solution:
def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:
seen = set()
stack = []
start = 0
for index, element in enumerate(popped):
while element not in seen:
stack.append(pushed[start] )
seen.add(pushed[start])
start += 1
catch = False
while catch == False:
if catch == False and len(stack) == 0:
return False
e = stack.pop()
if e == element:
catch = True
return True
# 1 2
# #given one element
# not seen: keep push until we see
# seen: keep pop until we seen
|
Given two sequences pushed and popped with distinct values, return true if and only if this could have been the result of a sequence of push and pop operations on an initially empty stack.
Example 1:
Input: pushed = [1,2,3,4,5], popped = [4,5,3,2,1]
Output: true
Explanation: We might do the following sequence:
push(1), push(2), push(3), push(4), pop() -> 4,
push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1
Example 2:
Input: pushed = [1,2,3,4,5], popped = [4,3,5,1,2]
Output: false
Explanation: 1 cannot be popped before 2.
Constraints:
0 <= pushed.length == popped.length <= 1000
0 <= pushed[i], popped[i] < 1000
pushed is a permutation of popped.
pushed and popped have distinct values.
|
class Solution:
def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:
stack = []
pop_index = 0
length = len(pushed)
for i in range(length):
stack.append(pushed[i])
while stack[-1] == popped[pop_index]:
print(stack)
stack.pop()
pop_index += 1
if pop_index >= length or len(stack) == 0:
break
continue
if len(stack) != 0:
return False
else:
return True
|
Given two sequences pushed and popped with distinct values, return true if and only if this could have been the result of a sequence of push and pop operations on an initially empty stack.
Example 1:
Input: pushed = [1,2,3,4,5], popped = [4,5,3,2,1]
Output: true
Explanation: We might do the following sequence:
push(1), push(2), push(3), push(4), pop() -> 4,
push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1
Example 2:
Input: pushed = [1,2,3,4,5], popped = [4,3,5,1,2]
Output: false
Explanation: 1 cannot be popped before 2.
Constraints:
0 <= pushed.length == popped.length <= 1000
0 <= pushed[i], popped[i] < 1000
pushed is a permutation of popped.
pushed and popped have distinct values.
|
class Solution:
def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:
if not pushed:
return True
temp = []
i = popiter = 0
while i < len(pushed):
if temp and temp[-1] == popped[popiter]:
print(temp,popped[popiter])
temp.pop()
popiter += 1
else:
temp.append(pushed[i])
i += 1
print(temp,popiter)
while temp:
if temp[-1]==popped[popiter]:
temp.pop()
popiter += 1
else:
return False
return True
|
In a 2 dimensional array grid, each value grid[i][j] represents the height of a building located there. We are allowed to increase the height of any number of buildings, by any amount (the amounts can be different for different buildings). Height 0 is considered to be a building as well.
At the end, the "skyline" when viewed from all four directions of the grid, i.e. top, bottom, left, and right, must be the same as the skyline of the original grid. A city's skyline is the outer contour of the rectangles formed by all the buildings when viewed from a distance. See the following example.
What is the maximum total sum that the height of the buildings can be increased?
Example:
Input: grid = [[3,0,8,4],[2,4,5,7],[9,2,6,3],[0,3,1,0]]
Output: 35
Explanation:
The grid is:
[ [3, 0, 8, 4],
[2, 4, 5, 7],
[9, 2, 6, 3],
[0, 3, 1, 0] ]
The skyline viewed from top or bottom is: [9, 4, 8, 7]
The skyline viewed from left or right is: [8, 7, 9, 3]
The grid after increasing the height of buildings without affecting skylines is:
gridNew = [ [8, 4, 8, 7],
[7, 4, 7, 7],
[9, 4, 8, 7],
[3, 3, 3, 3] ]
Notes:
1 < grid.length = grid[0].length <= 50.
All heights grid[i][j] are in the range [0, 100].
All buildings in grid[i][j] occupy the entire grid cell: that is, they are a 1 x 1 x grid[i][j] rectangular prism.
|
class Solution:
def maxIncreaseKeepingSkyline(self, grid: List[List[int]]) -> int:
# Pad with inf to make implementation easier
INF = -10_000
n = len(grid)
total = 0
max_rows = [max(row, default=INF) for row in grid]
# Transpose the grid to make max less cumbersome
max_cols = [max(col, default=INF) for col in zip(*grid)]
for i, best_row in enumerate(max_rows):
for j, best_col in enumerate(max_cols):
new_height = min(best_row, best_col)
total += new_height - grid[i][j]
return total
|
Given an integer n, you must transform it into 0 using the following operations any number of times:
Change the rightmost (0th) bit in the binary representation of n.
Change the ith bit in the binary representation of n if the (i-1)th bit is set to 1 and the (i-2)th through 0th bits are set to 0.
Return the minimum number of operations to transform n into 0.
Example 1:
Input: n = 0
Output: 0
Example 2:
Input: n = 3
Output: 2
Explanation: The binary representation of 3 is "11".
"11" -> "01" with the 2nd operation since the 0th bit is 1.
"01" -> "00" with the 1st operation.
Example 3:
Input: n = 6
Output: 4
Explanation: The binary representation of 6 is "110".
"110" -> "010" with the 2nd operation since the 1st bit is 1 and 0th through 0th bits are 0.
"010" -> "011" with the 1st operation.
"011" -> "001" with the 2nd operation since the 0th bit is 1.
"001" -> "000" with the 1st operation.
Example 4:
Input: n = 9
Output: 14
Example 5:
Input: n = 333
Output: 393
Constraints:
0 <= n <= 109
|
class Solution:
def minimumOneBitOperations(self, n: int) -> int:
s = 0
m = n
while m:
s += m & 1
m >>= 1
k = 1
while s:
s -= bool(n & k)
n ^= (s & 1) and k
k <<= 1
return n
|
Given an integer n, you must transform it into 0 using the following operations any number of times:
Change the rightmost (0th) bit in the binary representation of n.
Change the ith bit in the binary representation of n if the (i-1)th bit is set to 1 and the (i-2)th through 0th bits are set to 0.
Return the minimum number of operations to transform n into 0.
Example 1:
Input: n = 0
Output: 0
Example 2:
Input: n = 3
Output: 2
Explanation: The binary representation of 3 is "11".
"11" -> "01" with the 2nd operation since the 0th bit is 1.
"01" -> "00" with the 1st operation.
Example 3:
Input: n = 6
Output: 4
Explanation: The binary representation of 6 is "110".
"110" -> "010" with the 2nd operation since the 1st bit is 1 and 0th through 0th bits are 0.
"010" -> "011" with the 1st operation.
"011" -> "001" with the 2nd operation since the 0th bit is 1.
"001" -> "000" with the 1st operation.
Example 4:
Input: n = 9
Output: 14
Example 5:
Input: n = 333
Output: 393
Constraints:
0 <= n <= 109
|
class Solution:
def minimumOneBitOperations(self, n: int) -> int:
ans = 0
while n:
ans^=n
n//=2
return ans
|
Given an integer n, you must transform it into 0 using the following operations any number of times:
Change the rightmost (0th) bit in the binary representation of n.
Change the ith bit in the binary representation of n if the (i-1)th bit is set to 1 and the (i-2)th through 0th bits are set to 0.
Return the minimum number of operations to transform n into 0.
Example 1:
Input: n = 0
Output: 0
Example 2:
Input: n = 3
Output: 2
Explanation: The binary representation of 3 is "11".
"11" -> "01" with the 2nd operation since the 0th bit is 1.
"01" -> "00" with the 1st operation.
Example 3:
Input: n = 6
Output: 4
Explanation: The binary representation of 6 is "110".
"110" -> "010" with the 2nd operation since the 1st bit is 1 and 0th through 0th bits are 0.
"010" -> "011" with the 1st operation.
"011" -> "001" with the 2nd operation since the 0th bit is 1.
"001" -> "000" with the 1st operation.
Example 4:
Input: n = 9
Output: 14
Example 5:
Input: n = 333
Output: 393
Constraints:
0 <= n <= 109
|
class Solution:
def minimumOneBitOperations(self, n: int) -> int:
if n <= 1: return n
b = int(math.log2(n)) + 1
return ((1 << b)-1) - self.minimumOneBitOperations(n - (1 << (b-1)))
|
Given an integer n, you must transform it into 0 using the following operations any number of times:
Change the rightmost (0th) bit in the binary representation of n.
Change the ith bit in the binary representation of n if the (i-1)th bit is set to 1 and the (i-2)th through 0th bits are set to 0.
Return the minimum number of operations to transform n into 0.
Example 1:
Input: n = 0
Output: 0
Example 2:
Input: n = 3
Output: 2
Explanation: The binary representation of 3 is "11".
"11" -> "01" with the 2nd operation since the 0th bit is 1.
"01" -> "00" with the 1st operation.
Example 3:
Input: n = 6
Output: 4
Explanation: The binary representation of 6 is "110".
"110" -> "010" with the 2nd operation since the 1st bit is 1 and 0th through 0th bits are 0.
"010" -> "011" with the 1st operation.
"011" -> "001" with the 2nd operation since the 0th bit is 1.
"001" -> "000" with the 1st operation.
Example 4:
Input: n = 9
Output: 14
Example 5:
Input: n = 333
Output: 393
Constraints:
0 <= n <= 109
|
class Solution:
def minimumOneBitOperations(self, n: int) -> int:
result = 0
while n:
result = ((n & -n) << 1) - 1 - result
n -= n & -n
return result
|
Given an integer n, you must transform it into 0 using the following operations any number of times:
Change the rightmost (0th) bit in the binary representation of n.
Change the ith bit in the binary representation of n if the (i-1)th bit is set to 1 and the (i-2)th through 0th bits are set to 0.
Return the minimum number of operations to transform n into 0.
Example 1:
Input: n = 0
Output: 0
Example 2:
Input: n = 3
Output: 2
Explanation: The binary representation of 3 is "11".
"11" -> "01" with the 2nd operation since the 0th bit is 1.
"01" -> "00" with the 1st operation.
Example 3:
Input: n = 6
Output: 4
Explanation: The binary representation of 6 is "110".
"110" -> "010" with the 2nd operation since the 1st bit is 1 and 0th through 0th bits are 0.
"010" -> "011" with the 1st operation.
"011" -> "001" with the 2nd operation since the 0th bit is 1.
"001" -> "000" with the 1st operation.
Example 4:
Input: n = 9
Output: 14
Example 5:
Input: n = 333
Output: 393
Constraints:
0 <= n <= 109
|
from functools import lru_cache
# removehigh = [(1 << l) - 1 for l in range(31)]
@lru_cache()
def removehigh(l: int) -> int:
if l <= 1:
return l + 1
return (1 << l)
@lru_cache()
def sethigh(l: int, n: int) -> int:
if n == 0:
return removehigh(l) - 1
t2 = 1 << l - 2
if n >= t2:
return removehigh(l - 1) + remove(n - t2)
if n & (n - 1) == 0:
return removehigh(l) - removehigh(n.bit_length())
return removehigh(l - 1) + sethigh(l - 1, n)
@lru_cache()
def remove(n: int) -> int:
if n <= 1:
return n
elif n <= 3:
return 5 - n
l = n.bit_length()
if n & (n - 1) == 0:
return removehigh(l) - 1
t3 = 3 << l - 2
if n >= t3:
return removehigh(l - 1) + remove(n - t3)
t1 = 1 << l - 1
return removehigh(l - 1) + sethigh(l - 1, n - t1)
class Solution:
def minimumOneBitOperations(self, n: int) -> int:
return remove(n)
|
Given an integer n, you must transform it into 0 using the following operations any number of times:
Change the rightmost (0th) bit in the binary representation of n.
Change the ith bit in the binary representation of n if the (i-1)th bit is set to 1 and the (i-2)th through 0th bits are set to 0.
Return the minimum number of operations to transform n into 0.
Example 1:
Input: n = 0
Output: 0
Example 2:
Input: n = 3
Output: 2
Explanation: The binary representation of 3 is "11".
"11" -> "01" with the 2nd operation since the 0th bit is 1.
"01" -> "00" with the 1st operation.
Example 3:
Input: n = 6
Output: 4
Explanation: The binary representation of 6 is "110".
"110" -> "010" with the 2nd operation since the 1st bit is 1 and 0th through 0th bits are 0.
"010" -> "011" with the 1st operation.
"011" -> "001" with the 2nd operation since the 0th bit is 1.
"001" -> "000" with the 1st operation.
Example 4:
Input: n = 9
Output: 14
Example 5:
Input: n = 333
Output: 393
Constraints:
0 <= n <= 109
|
class Solution:
def minimumOneBitOperations(self, n: int) -> int:
ans = 0
while n>0:
ans = ans^n
n = n>>1
return ans
|
Given an integer n, you must transform it into 0 using the following operations any number of times:
Change the rightmost (0th) bit in the binary representation of n.
Change the ith bit in the binary representation of n if the (i-1)th bit is set to 1 and the (i-2)th through 0th bits are set to 0.
Return the minimum number of operations to transform n into 0.
Example 1:
Input: n = 0
Output: 0
Example 2:
Input: n = 3
Output: 2
Explanation: The binary representation of 3 is "11".
"11" -> "01" with the 2nd operation since the 0th bit is 1.
"01" -> "00" with the 1st operation.
Example 3:
Input: n = 6
Output: 4
Explanation: The binary representation of 6 is "110".
"110" -> "010" with the 2nd operation since the 1st bit is 1 and 0th through 0th bits are 0.
"010" -> "011" with the 1st operation.
"011" -> "001" with the 2nd operation since the 0th bit is 1.
"001" -> "000" with the 1st operation.
Example 4:
Input: n = 9
Output: 14
Example 5:
Input: n = 333
Output: 393
Constraints:
0 <= n <= 109
|
class Solution:
def minimumOneBitOperations(self, n: int) -> int:
if n == 0:
return 0
if n == 1:
return 1
tot = 0
b = bin(n)[2:]
if b[1] == '0':
tot += 2**(len(b)-2)
lastChanged = b[1] == '0'
for i in range(2,len(b)):
if (lastChanged and b[i] == '0') or (not lastChanged and b[i] == '1'):
tot += 2**(len(b)-1-i)
lastChanged = True
else:
lastChanged = False
return tot + 1 + self.minimumOneBitOperations(int('1' + '0'*(len(b)-2),2))
|
Given an integer n, you must transform it into 0 using the following operations any number of times:
Change the rightmost (0th) bit in the binary representation of n.
Change the ith bit in the binary representation of n if the (i-1)th bit is set to 1 and the (i-2)th through 0th bits are set to 0.
Return the minimum number of operations to transform n into 0.
Example 1:
Input: n = 0
Output: 0
Example 2:
Input: n = 3
Output: 2
Explanation: The binary representation of 3 is "11".
"11" -> "01" with the 2nd operation since the 0th bit is 1.
"01" -> "00" with the 1st operation.
Example 3:
Input: n = 6
Output: 4
Explanation: The binary representation of 6 is "110".
"110" -> "010" with the 2nd operation since the 1st bit is 1 and 0th through 0th bits are 0.
"010" -> "011" with the 1st operation.
"011" -> "001" with the 2nd operation since the 0th bit is 1.
"001" -> "000" with the 1st operation.
Example 4:
Input: n = 9
Output: 14
Example 5:
Input: n = 333
Output: 393
Constraints:
0 <= n <= 109
|
from functools import lru_cache
class Solution:
def minimumOneBitOperations(self, n: int) -> int:
return self.toZero(n)
@lru_cache(maxsize=None)
def toZero(self, n):
if n <= 1:
return n
elif n == 2:
return 3
elif n == 3:
return 2
offset = 0
while ((1 << (offset + 1)) - 1) & n != n:
offset += 1
target = 1 << (offset - 1)
return self.topower2(n & ((target << 1) - 1), target) + 1 + self.toZero(target)
@lru_cache(maxsize=None)
def topower2(self, n, target):
if n == 0:
return 1 + self.topower2(1, target)
elif n == target:
return 0
offset = 0
while ((1 << (offset + 1)) - 1) & n != n:
offset += 1
if n & target == 0:
return self.topower2(n, target >> 1) + 1 + self.toZero(target >> 1)
return self.toZero(n & (target - 1))
|
Given an array of integers nums, find the maximum length of a subarray where the product of all its elements is positive.
A subarray of an array is a consecutive sequence of zero or more values taken out of that array.
Return the maximum length of a subarray with positive product.
Example 1:
Input: nums = [1,-2,-3,4]
Output: 4
Explanation: The array nums already has a positive product of 24.
Example 2:
Input: nums = [0,1,-2,-3,-4]
Output: 3
Explanation: The longest subarray with positive product is [1,-2,-3] which has a product of 6.
Notice that we cannot include 0 in the subarray since that'll make the product 0 which is not positive.
Example 3:
Input: nums = [-1,-2,-3,0,1]
Output: 2
Explanation: The longest subarray with positive product is [-1,-2] or [-2,-3].
Example 4:
Input: nums = [-1,2]
Output: 1
Example 5:
Input: nums = [1,2,3,5,-6,4,0,10]
Output: 4
Constraints:
1 <= nums.length <= 10^5
-10^9 <= nums[i] <= 10^9
|
class Solution:
def getMaxLen(self, nums: List[int]) -> int:
maxx = 0
nums.append(0)
# starting position
# where we find a 0
i = -1
minusarr = []
for j,n in enumerate(nums):
if n == 0:
# now figure out previous ones
tot = j-i-1
if not minusarr or len(minusarr)%2 == 0:
maxx = max(maxx, tot)
else:
# drop the first or last 0
left = minusarr[0]-i
right = j-minusarr[-1]
maxx = max(maxx, tot - min(left, right))
# reinitiate
minusarr = []
i = j
elif n < 0:
minusarr.append(j)
return maxx
|
Given an array of integers nums, find the maximum length of a subarray where the product of all its elements is positive.
A subarray of an array is a consecutive sequence of zero or more values taken out of that array.
Return the maximum length of a subarray with positive product.
Example 1:
Input: nums = [1,-2,-3,4]
Output: 4
Explanation: The array nums already has a positive product of 24.
Example 2:
Input: nums = [0,1,-2,-3,-4]
Output: 3
Explanation: The longest subarray with positive product is [1,-2,-3] which has a product of 6.
Notice that we cannot include 0 in the subarray since that'll make the product 0 which is not positive.
Example 3:
Input: nums = [-1,-2,-3,0,1]
Output: 2
Explanation: The longest subarray with positive product is [-1,-2] or [-2,-3].
Example 4:
Input: nums = [-1,2]
Output: 1
Example 5:
Input: nums = [1,2,3,5,-6,4,0,10]
Output: 4
Constraints:
1 <= nums.length <= 10^5
-10^9 <= nums[i] <= 10^9
|
class Solution:
def getMaxLen(self, a: List[int], having_zero=True) -> int:
if not a: return 0
if having_zero:
zeros = [i for i, x in enumerate(a) if x == 0]
ans, prev = -float('inf'), 0
for i in zeros:
ans = max(ans, self.getMaxLen(a[prev:i], False))
prev = i+1
ans = max(ans, self.getMaxLen(a[prev:], False))
return ans
negs = [i for i, x in enumerate(a) if x < 0]
if len(negs) % 2 == 0: return len(a)
return max(negs[-1], len(a) - negs[0] - 1)
|
Given an array of integers nums, find the maximum length of a subarray where the product of all its elements is positive.
A subarray of an array is a consecutive sequence of zero or more values taken out of that array.
Return the maximum length of a subarray with positive product.
Example 1:
Input: nums = [1,-2,-3,4]
Output: 4
Explanation: The array nums already has a positive product of 24.
Example 2:
Input: nums = [0,1,-2,-3,-4]
Output: 3
Explanation: The longest subarray with positive product is [1,-2,-3] which has a product of 6.
Notice that we cannot include 0 in the subarray since that'll make the product 0 which is not positive.
Example 3:
Input: nums = [-1,-2,-3,0,1]
Output: 2
Explanation: The longest subarray with positive product is [-1,-2] or [-2,-3].
Example 4:
Input: nums = [-1,2]
Output: 1
Example 5:
Input: nums = [1,2,3,5,-6,4,0,10]
Output: 4
Constraints:
1 <= nums.length <= 10^5
-10^9 <= nums[i] <= 10^9
|
class Solution:
def getMaxLen(self, nums: List[int]) -> int:
# Greedy alg
l = len(nums)
start = 0
subArrays = []
for i in range(l):
if nums[i] == 0:
subArrays.append(self.findOptimal(nums[start:i]))
start = i+1
end = i+1
subArrays.append(self.findOptimal(nums[start:l]))
return max(subArrays)
def findOptimal(self, nums: List[int]) -> int:
if not nums:
return 0
negs = 0
l = 0
for i in nums:
l += 1
if i < 0: negs += 1
if negs % 2 == 0:
return l
else:
# Two pointers approach
i = 0
j = l - 1
while i < j:
if nums[i] < 0 or nums[j] < 0:
return l - 1
i += 1
j -= 1
l -= 1
#return max(self.findOptimal(nums[1:]), self.findOptimal(nums[:-1]))
return 0
|
Given an array of integers nums, find the maximum length of a subarray where the product of all its elements is positive.
A subarray of an array is a consecutive sequence of zero or more values taken out of that array.
Return the maximum length of a subarray with positive product.
Example 1:
Input: nums = [1,-2,-3,4]
Output: 4
Explanation: The array nums already has a positive product of 24.
Example 2:
Input: nums = [0,1,-2,-3,-4]
Output: 3
Explanation: The longest subarray with positive product is [1,-2,-3] which has a product of 6.
Notice that we cannot include 0 in the subarray since that'll make the product 0 which is not positive.
Example 3:
Input: nums = [-1,-2,-3,0,1]
Output: 2
Explanation: The longest subarray with positive product is [-1,-2] or [-2,-3].
Example 4:
Input: nums = [-1,2]
Output: 1
Example 5:
Input: nums = [1,2,3,5,-6,4,0,10]
Output: 4
Constraints:
1 <= nums.length <= 10^5
-10^9 <= nums[i] <= 10^9
|
class Solution:
def getMaxLen(self, nums: List[int]) -> int:
pos_p=0
neg_p=0
pos,neg=0,0
result=0
for i in range( len(nums)):
pos_p,neg_p=pos,neg
if nums[i] > 0:
pos= 1 + pos_p
neg= 1 + neg_p if neg_p > 0 else 0
elif nums[i] < 0:
pos= (1 + neg_p) if neg_p > 0 else 0
neg= (1 + pos_p) if pos_p > 0 else 1
else:
pos,neg=0,0
result=max(result, pos)
return result
|
Given an array of integers nums, find the maximum length of a subarray where the product of all its elements is positive.
A subarray of an array is a consecutive sequence of zero or more values taken out of that array.
Return the maximum length of a subarray with positive product.
Example 1:
Input: nums = [1,-2,-3,4]
Output: 4
Explanation: The array nums already has a positive product of 24.
Example 2:
Input: nums = [0,1,-2,-3,-4]
Output: 3
Explanation: The longest subarray with positive product is [1,-2,-3] which has a product of 6.
Notice that we cannot include 0 in the subarray since that'll make the product 0 which is not positive.
Example 3:
Input: nums = [-1,-2,-3,0,1]
Output: 2
Explanation: The longest subarray with positive product is [-1,-2] or [-2,-3].
Example 4:
Input: nums = [-1,2]
Output: 1
Example 5:
Input: nums = [1,2,3,5,-6,4,0,10]
Output: 4
Constraints:
1 <= nums.length <= 10^5
-10^9 <= nums[i] <= 10^9
|
class Solution:
def getMaxLen(self, nums: List[int]) -> int:
# 3:58 9/1/2020
# Max len of subarray with positive Product
last={1:-1}
pro=1
ans=0
for i,c in enumerate(nums):
pro = c * pro / abs(pro) if pro != 0 else 0
if pro>0:
ans=max(i-last[1],ans)
elif pro<0:
if -1 in last:
ans=max(ans,i-last[-1])
else:
last[-1]=i
elif pro==0:
pro=1
last={}
last[1]=i
return ans
|
Given an array of integers nums, find the maximum length of a subarray where the product of all its elements is positive.
A subarray of an array is a consecutive sequence of zero or more values taken out of that array.
Return the maximum length of a subarray with positive product.
Example 1:
Input: nums = [1,-2,-3,4]
Output: 4
Explanation: The array nums already has a positive product of 24.
Example 2:
Input: nums = [0,1,-2,-3,-4]
Output: 3
Explanation: The longest subarray with positive product is [1,-2,-3] which has a product of 6.
Notice that we cannot include 0 in the subarray since that'll make the product 0 which is not positive.
Example 3:
Input: nums = [-1,-2,-3,0,1]
Output: 2
Explanation: The longest subarray with positive product is [-1,-2] or [-2,-3].
Example 4:
Input: nums = [-1,2]
Output: 1
Example 5:
Input: nums = [1,2,3,5,-6,4,0,10]
Output: 4
Constraints:
1 <= nums.length <= 10^5
-10^9 <= nums[i] <= 10^9
|
class Solution:
def getMaxLen(self, nums: List[int]) -> int:
n = len(nums)
dp = [[0] * (n+1) for i in range(2)]
for i, x in enumerate(nums):
if x > 0:
dp[0][i+1] = dp[0][i] + 1
if dp[1][i] > 0:
dp[1][i+1] = dp[1][i] + 1
elif x < 0:
if dp[1][i] > 0:
dp[0][i+1] = dp[1][i] + 1
dp[1][i+1] = dp[0][i] + 1
else:
dp[0][i+1] = dp[1][i+1] = 0
# print(dp)
return max(dp[0])
|
Given an array of integers nums, find the maximum length of a subarray where the product of all its elements is positive.
A subarray of an array is a consecutive sequence of zero or more values taken out of that array.
Return the maximum length of a subarray with positive product.
Example 1:
Input: nums = [1,-2,-3,4]
Output: 4
Explanation: The array nums already has a positive product of 24.
Example 2:
Input: nums = [0,1,-2,-3,-4]
Output: 3
Explanation: The longest subarray with positive product is [1,-2,-3] which has a product of 6.
Notice that we cannot include 0 in the subarray since that'll make the product 0 which is not positive.
Example 3:
Input: nums = [-1,-2,-3,0,1]
Output: 2
Explanation: The longest subarray with positive product is [-1,-2] or [-2,-3].
Example 4:
Input: nums = [-1,2]
Output: 1
Example 5:
Input: nums = [1,2,3,5,-6,4,0,10]
Output: 4
Constraints:
1 <= nums.length <= 10^5
-10^9 <= nums[i] <= 10^9
|
class Solution:
def getMaxLen(self, nums: List[int]) -> int:
n=len(nums)
pos,neg=0,0
[0,1,-2,-3,-4]
if nums[0]>0:
pos=1
if nums[0]<0:
neg=1
ans=pos
for i in range(1,n):
if nums[i]>0:
pos = 1 + pos
neg = 1 + neg if neg >0 else 0
elif nums[i]<0:
pre_pos,pre_neg=pos,neg
pos= 1 + pre_neg if pre_neg >0 else 0
neg = 1 + pre_pos
else:
pos,neg =0,0
ans = max(ans,pos)
return ans
|
Given an array of integers nums, find the maximum length of a subarray where the product of all its elements is positive.
A subarray of an array is a consecutive sequence of zero or more values taken out of that array.
Return the maximum length of a subarray with positive product.
Example 1:
Input: nums = [1,-2,-3,4]
Output: 4
Explanation: The array nums already has a positive product of 24.
Example 2:
Input: nums = [0,1,-2,-3,-4]
Output: 3
Explanation: The longest subarray with positive product is [1,-2,-3] which has a product of 6.
Notice that we cannot include 0 in the subarray since that'll make the product 0 which is not positive.
Example 3:
Input: nums = [-1,-2,-3,0,1]
Output: 2
Explanation: The longest subarray with positive product is [-1,-2] or [-2,-3].
Example 4:
Input: nums = [-1,2]
Output: 1
Example 5:
Input: nums = [1,2,3,5,-6,4,0,10]
Output: 4
Constraints:
1 <= nums.length <= 10^5
-10^9 <= nums[i] <= 10^9
|
class Solution:
def getMaxLen(self, nums: List[int]) -> int:
plus,minus,res,c = 0,-1,0,0
for i in range(0,len(nums)):
if nums[i] == 0:
if c%2 == 1:
res = max(res,minus)
else:
res = max(res,max(plus,minus))
plus,minus,c = 0,-1,0
elif nums[i] > 0:
if minus != -1:
minus += 1
plus += 1
else:
c += 1
minus += 1
if c%2 == 1:
res = max(res,max(minus,plus))
plus += 1
if c%2 == 1:
res = max(res,minus)
else:
res = max(res,max(plus,minus))
return res
|
Given an array of integers nums, find the maximum length of a subarray where the product of all its elements is positive.
A subarray of an array is a consecutive sequence of zero or more values taken out of that array.
Return the maximum length of a subarray with positive product.
Example 1:
Input: nums = [1,-2,-3,4]
Output: 4
Explanation: The array nums already has a positive product of 24.
Example 2:
Input: nums = [0,1,-2,-3,-4]
Output: 3
Explanation: The longest subarray with positive product is [1,-2,-3] which has a product of 6.
Notice that we cannot include 0 in the subarray since that'll make the product 0 which is not positive.
Example 3:
Input: nums = [-1,-2,-3,0,1]
Output: 2
Explanation: The longest subarray with positive product is [-1,-2] or [-2,-3].
Example 4:
Input: nums = [-1,2]
Output: 1
Example 5:
Input: nums = [1,2,3,5,-6,4,0,10]
Output: 4
Constraints:
1 <= nums.length <= 10^5
-10^9 <= nums[i] <= 10^9
|
class Solution:
def getMaxLen(self, nums: List[int]) -> int:
n = len(nums)
pos, neg = [0] * n, [0] * n
if nums[0] > 0: pos[0] = 1
if nums[0] < 0: neg[0] = 1
ans = pos[0]
for i in range(1, n):
if nums[i] > 0:
pos[i] = 1 + pos[i - 1]
neg[i] = 1 + neg[i - 1] if neg[i - 1] > 0 else 0
elif nums[i] < 0:
pos[i] = 1 + neg[i - 1] if neg[i - 1] > 0 else 0
neg[i] = 1 + pos[i - 1]
ans = max(ans, pos[i])
return ans
|
Given an array of integers nums, find the maximum length of a subarray where the product of all its elements is positive.
A subarray of an array is a consecutive sequence of zero or more values taken out of that array.
Return the maximum length of a subarray with positive product.
Example 1:
Input: nums = [1,-2,-3,4]
Output: 4
Explanation: The array nums already has a positive product of 24.
Example 2:
Input: nums = [0,1,-2,-3,-4]
Output: 3
Explanation: The longest subarray with positive product is [1,-2,-3] which has a product of 6.
Notice that we cannot include 0 in the subarray since that'll make the product 0 which is not positive.
Example 3:
Input: nums = [-1,-2,-3,0,1]
Output: 2
Explanation: The longest subarray with positive product is [-1,-2] or [-2,-3].
Example 4:
Input: nums = [-1,2]
Output: 1
Example 5:
Input: nums = [1,2,3,5,-6,4,0,10]
Output: 4
Constraints:
1 <= nums.length <= 10^5
-10^9 <= nums[i] <= 10^9
|
class Solution:
def getMaxLen(self, nums: List[int]) -> int:
def solve(nums):
cnt = 0
for n in nums:
if n < 0:
cnt += 1
if cnt%2 == 0:
return len(nums)
for i in range(len(nums)):
if nums[i] < 0:
first = i
break
for i in range(len(nums)-1, -1, -1):
if nums[i] < 0:
last = i
break
return max(last, len(nums)-first-1)
l = 0
ans = 0
nums.append(0)
for r in range(len(nums)):
if nums[r] == 0:
cur = solve(nums[l:r])
ans = max(ans, cur)
l = r+1
return ans
|
Given an array of integers nums, find the maximum length of a subarray where the product of all its elements is positive.
A subarray of an array is a consecutive sequence of zero or more values taken out of that array.
Return the maximum length of a subarray with positive product.
Example 1:
Input: nums = [1,-2,-3,4]
Output: 4
Explanation: The array nums already has a positive product of 24.
Example 2:
Input: nums = [0,1,-2,-3,-4]
Output: 3
Explanation: The longest subarray with positive product is [1,-2,-3] which has a product of 6.
Notice that we cannot include 0 in the subarray since that'll make the product 0 which is not positive.
Example 3:
Input: nums = [-1,-2,-3,0,1]
Output: 2
Explanation: The longest subarray with positive product is [-1,-2] or [-2,-3].
Example 4:
Input: nums = [-1,2]
Output: 1
Example 5:
Input: nums = [1,2,3,5,-6,4,0,10]
Output: 4
Constraints:
1 <= nums.length <= 10^5
-10^9 <= nums[i] <= 10^9
|
class Solution:
def getMaxLen(self, nums: List[int]) -> int:
@lru_cache(None)
def pos_helper(len):
if len == 0:
return 0
if len == 1:
return 1 if nums[0] > 0 else 0
if nums[len - 1] > 0:
return pos_helper(len - 1) + 1
if nums[len - 1] == 0:
return 0
if nums[len - 1] < 0:
return neg_helper(len - 1) + 1 if neg_helper(len - 1) != 0 else 0
@lru_cache(None)
def neg_helper(len):
if len == 0:
return 0
if len == 1:
return 1 if nums[0] < 0 else 0
if nums[len - 1] > 0:
return neg_helper(len - 1) + 1 if neg_helper(len - 1) > 0 else 0
if nums[len - 1] == 0:
return 0
if nums[len - 1] < 0:
return pos_helper(len - 1) + 1
res = 0
for i in range(0, len(nums) + 1):
res = max(res, pos_helper(i))
return res
|
Given an array of integers nums, find the maximum length of a subarray where the product of all its elements is positive.
A subarray of an array is a consecutive sequence of zero or more values taken out of that array.
Return the maximum length of a subarray with positive product.
Example 1:
Input: nums = [1,-2,-3,4]
Output: 4
Explanation: The array nums already has a positive product of 24.
Example 2:
Input: nums = [0,1,-2,-3,-4]
Output: 3
Explanation: The longest subarray with positive product is [1,-2,-3] which has a product of 6.
Notice that we cannot include 0 in the subarray since that'll make the product 0 which is not positive.
Example 3:
Input: nums = [-1,-2,-3,0,1]
Output: 2
Explanation: The longest subarray with positive product is [-1,-2] or [-2,-3].
Example 4:
Input: nums = [-1,2]
Output: 1
Example 5:
Input: nums = [1,2,3,5,-6,4,0,10]
Output: 4
Constraints:
1 <= nums.length <= 10^5
-10^9 <= nums[i] <= 10^9
|
class Solution:
def getMaxLen(self, nums: List[int]) -> int:
n = len(nums)
pos, neg = 0, 0
if nums[0] > 0: pos = 1
if nums[0] < 0: neg = 1
ans = pos
for i in range(1, n):
if nums[i] > 0:
pos_next = 1 + pos
neg_next = 1 + neg if neg > 0 else 0
elif nums[i] < 0:
pos_next = 1 + neg if neg > 0 else 0
neg_next = 1 + pos
else:
pos_next, neg_next = 0, 0
pos, neg = pos_next, neg_next
ans = max(ans, pos)
return ans
|
Given an array of integers nums, find the maximum length of a subarray where the product of all its elements is positive.
A subarray of an array is a consecutive sequence of zero or more values taken out of that array.
Return the maximum length of a subarray with positive product.
Example 1:
Input: nums = [1,-2,-3,4]
Output: 4
Explanation: The array nums already has a positive product of 24.
Example 2:
Input: nums = [0,1,-2,-3,-4]
Output: 3
Explanation: The longest subarray with positive product is [1,-2,-3] which has a product of 6.
Notice that we cannot include 0 in the subarray since that'll make the product 0 which is not positive.
Example 3:
Input: nums = [-1,-2,-3,0,1]
Output: 2
Explanation: The longest subarray with positive product is [-1,-2] or [-2,-3].
Example 4:
Input: nums = [-1,2]
Output: 1
Example 5:
Input: nums = [1,2,3,5,-6,4,0,10]
Output: 4
Constraints:
1 <= nums.length <= 10^5
-10^9 <= nums[i] <= 10^9
|
class Solution:
def getMaxLen(self, nums: List[int]) -> int:
maxlen = 0
curlen = 0
tmplen = 0
even = True
for i in nums:
if i == 0:
if tmplen != curlen:
# We meet odd numbers of negative number, check if the rest is larger
maxlen = max(maxlen, tmplen - curlen - 1)
maxlen = max(maxlen, curlen)
curlen = 0
tmplen = 0
even = True
continue
tmplen += 1
if i < 0:
even = not even
if even == True:
curlen = tmplen
if i > 0 and even == True:
curlen += 1
if tmplen != curlen:
# We meet odd numbers of negative number, check if the rest is larger
maxlen = max(maxlen, tmplen - curlen - 1)
maxlen = max(maxlen, curlen)
curlen = 0
tmplen = 0
even = True
for i in reversed(nums):
if i == 0:
if tmplen != curlen:
# We meet odd numbers of negative number, check if the rest is larger
maxlen = max(maxlen, tmplen - curlen - 1)
maxlen = max(maxlen, curlen)
curlen = 0
tmplen = 0
even = True
continue
tmplen += 1
if i < 0:
even = not even
if even == True:
curlen = tmplen
if i > 0 and even == True:
curlen += 1
if tmplen != curlen:
# We meet odd numbers of negative number, check if the rest is larger
maxlen = max(maxlen, tmplen - curlen - 1)
maxlen = max(maxlen, curlen)
return maxlen
|
Given an array of integers nums, find the maximum length of a subarray where the product of all its elements is positive.
A subarray of an array is a consecutive sequence of zero or more values taken out of that array.
Return the maximum length of a subarray with positive product.
Example 1:
Input: nums = [1,-2,-3,4]
Output: 4
Explanation: The array nums already has a positive product of 24.
Example 2:
Input: nums = [0,1,-2,-3,-4]
Output: 3
Explanation: The longest subarray with positive product is [1,-2,-3] which has a product of 6.
Notice that we cannot include 0 in the subarray since that'll make the product 0 which is not positive.
Example 3:
Input: nums = [-1,-2,-3,0,1]
Output: 2
Explanation: The longest subarray with positive product is [-1,-2] or [-2,-3].
Example 4:
Input: nums = [-1,2]
Output: 1
Example 5:
Input: nums = [1,2,3,5,-6,4,0,10]
Output: 4
Constraints:
1 <= nums.length <= 10^5
-10^9 <= nums[i] <= 10^9
|
class Solution:
def getMaxLen(self, nums: List[int]) -> int:
pos = 1 if nums[0]>0 else 0
neg = 1 if nums[0]<0 else 0
ans = pos
for i in range(1,len(nums)):
if nums[i]>0:
pos = 1+pos
neg = 1+neg if neg>0 else 0
elif nums[i]<0:
pre_pos = pos
pos = 1+neg if neg>0 else 0
neg = 1+pre_pos
else:
pos, neg = 0, 0
ans = max(ans,pos)
return ans
|
Given an array of integers nums, find the maximum length of a subarray where the product of all its elements is positive.
A subarray of an array is a consecutive sequence of zero or more values taken out of that array.
Return the maximum length of a subarray with positive product.
Example 1:
Input: nums = [1,-2,-3,4]
Output: 4
Explanation: The array nums already has a positive product of 24.
Example 2:
Input: nums = [0,1,-2,-3,-4]
Output: 3
Explanation: The longest subarray with positive product is [1,-2,-3] which has a product of 6.
Notice that we cannot include 0 in the subarray since that'll make the product 0 which is not positive.
Example 3:
Input: nums = [-1,-2,-3,0,1]
Output: 2
Explanation: The longest subarray with positive product is [-1,-2] or [-2,-3].
Example 4:
Input: nums = [-1,2]
Output: 1
Example 5:
Input: nums = [1,2,3,5,-6,4,0,10]
Output: 4
Constraints:
1 <= nums.length <= 10^5
-10^9 <= nums[i] <= 10^9
|
class Solution:
def getMaxLen(self, nums: List[int]) -> int:
result = 0
negativeIndices = []
currentProduct = 1
startIndex = 0
for index,number in enumerate(nums):
if number == 0:
negativeIndices = []
currentProduct = 1
startIndex = index + 1
continue
if number * currentProduct > 0:
result = max(result,index-startIndex+1)
currentProduct = 1
else:
if len(negativeIndices) != 0:
result = max(result,index-negativeIndices[0])
currentProduct = -1
if number < 0 and len(negativeIndices) == 0:
negativeIndices.append(index)
return result
|
Given an array of integers nums, find the maximum length of a subarray where the product of all its elements is positive.
A subarray of an array is a consecutive sequence of zero or more values taken out of that array.
Return the maximum length of a subarray with positive product.
Example 1:
Input: nums = [1,-2,-3,4]
Output: 4
Explanation: The array nums already has a positive product of 24.
Example 2:
Input: nums = [0,1,-2,-3,-4]
Output: 3
Explanation: The longest subarray with positive product is [1,-2,-3] which has a product of 6.
Notice that we cannot include 0 in the subarray since that'll make the product 0 which is not positive.
Example 3:
Input: nums = [-1,-2,-3,0,1]
Output: 2
Explanation: The longest subarray with positive product is [-1,-2] or [-2,-3].
Example 4:
Input: nums = [-1,2]
Output: 1
Example 5:
Input: nums = [1,2,3,5,-6,4,0,10]
Output: 4
Constraints:
1 <= nums.length <= 10^5
-10^9 <= nums[i] <= 10^9
|
class Solution:
def getMaxLen(self, A: List[int], cnt = 0, best = 0) -> int:
A.append(0) # ⭐️ sentinel value
N = len(A)
i = 0
j = 0
while i < N:
while j < N and not A[j]: # ➖ case 1: collapse window [i \\U0001f449 ..j]
while i < j:
cnt = cnt - 1 if A[i] < 0 else cnt; i += 1
best = best if cnt & 1 else max(best, j - i)
i = j + 1
j = j + 1
while j < N and A[j]: # ➕ case 2: expand window [i..j \\U0001f449 ]
cnt = cnt + 1 if A[j] < 0 else cnt; j += 1
best = best if cnt & 1 else max(best, j - i)
return best
|
Given an array of integers nums, find the maximum length of a subarray where the product of all its elements is positive.
A subarray of an array is a consecutive sequence of zero or more values taken out of that array.
Return the maximum length of a subarray with positive product.
Example 1:
Input: nums = [1,-2,-3,4]
Output: 4
Explanation: The array nums already has a positive product of 24.
Example 2:
Input: nums = [0,1,-2,-3,-4]
Output: 3
Explanation: The longest subarray with positive product is [1,-2,-3] which has a product of 6.
Notice that we cannot include 0 in the subarray since that'll make the product 0 which is not positive.
Example 3:
Input: nums = [-1,-2,-3,0,1]
Output: 2
Explanation: The longest subarray with positive product is [-1,-2] or [-2,-3].
Example 4:
Input: nums = [-1,2]
Output: 1
Example 5:
Input: nums = [1,2,3,5,-6,4,0,10]
Output: 4
Constraints:
1 <= nums.length <= 10^5
-10^9 <= nums[i] <= 10^9
|
class Solution:
def getMaxLen(self, nums: List[int]) -> int:
pos = 0
neg = 0
negIndex = 0
res = 0
for i in range(len(nums)):
if nums[i] == 0:
pos = 0
neg = 0
elif nums[i] > 0:
pos += 1
else:
neg += 1
if neg == 1:
negIndex = i
if neg % 2 == 0:
res = max(res, pos + neg)
else:
res = max(res, i - negIndex)
return res
|
Given an array of integers nums, find the maximum length of a subarray where the product of all its elements is positive.
A subarray of an array is a consecutive sequence of zero or more values taken out of that array.
Return the maximum length of a subarray with positive product.
Example 1:
Input: nums = [1,-2,-3,4]
Output: 4
Explanation: The array nums already has a positive product of 24.
Example 2:
Input: nums = [0,1,-2,-3,-4]
Output: 3
Explanation: The longest subarray with positive product is [1,-2,-3] which has a product of 6.
Notice that we cannot include 0 in the subarray since that'll make the product 0 which is not positive.
Example 3:
Input: nums = [-1,-2,-3,0,1]
Output: 2
Explanation: The longest subarray with positive product is [-1,-2] or [-2,-3].
Example 4:
Input: nums = [-1,2]
Output: 1
Example 5:
Input: nums = [1,2,3,5,-6,4,0,10]
Output: 4
Constraints:
1 <= nums.length <= 10^5
-10^9 <= nums[i] <= 10^9
|
class Solution:
def getMaxLen(self, nums: List[int]) -> int:
pointer1=0
pointer2=0
res=0
while(pointer1<len(nums)):
if nums[pointer1]==0:
pointer1+=1
continue
pointer2=pointer1
count=0
start=0
end=0
while(pointer2<len(nums) and nums[pointer2]!=0):
if nums[pointer2]<0:
count+=1
if count==1:
start=pointer2
end=pointer2
pointer2+=1
if count%2==0:
res=max(res,pointer2-pointer1)
else:
res=max(res,end-pointer1,pointer2-start-1)
pointer1=pointer2
return res
|
Given an array of integers nums, find the maximum length of a subarray where the product of all its elements is positive.
A subarray of an array is a consecutive sequence of zero or more values taken out of that array.
Return the maximum length of a subarray with positive product.
Example 1:
Input: nums = [1,-2,-3,4]
Output: 4
Explanation: The array nums already has a positive product of 24.
Example 2:
Input: nums = [0,1,-2,-3,-4]
Output: 3
Explanation: The longest subarray with positive product is [1,-2,-3] which has a product of 6.
Notice that we cannot include 0 in the subarray since that'll make the product 0 which is not positive.
Example 3:
Input: nums = [-1,-2,-3,0,1]
Output: 2
Explanation: The longest subarray with positive product is [-1,-2] or [-2,-3].
Example 4:
Input: nums = [-1,2]
Output: 1
Example 5:
Input: nums = [1,2,3,5,-6,4,0,10]
Output: 4
Constraints:
1 <= nums.length <= 10^5
-10^9 <= nums[i] <= 10^9
|
class Solution:
def getMaxLen(self, nums: List[int]) -> int:
if not nums: return 0
n = len(nums)
negNum = 0
firstNegIdx = -1
zeroPos = -1
res = 0
for i, num in enumerate(nums):
if num < 0:
negNum += 1
if firstNegIdx < 0: firstNegIdx = i
if num == 0:
negNum = 0
firstNegIdx = -1
zeroPos = i
else:
if negNum % 2 == 0:
res = max(res, i - zeroPos)
else:
res = max(res, i - firstNegIdx)
return res
|
Given an array of integers nums, find the maximum length of a subarray where the product of all its elements is positive.
A subarray of an array is a consecutive sequence of zero or more values taken out of that array.
Return the maximum length of a subarray with positive product.
Example 1:
Input: nums = [1,-2,-3,4]
Output: 4
Explanation: The array nums already has a positive product of 24.
Example 2:
Input: nums = [0,1,-2,-3,-4]
Output: 3
Explanation: The longest subarray with positive product is [1,-2,-3] which has a product of 6.
Notice that we cannot include 0 in the subarray since that'll make the product 0 which is not positive.
Example 3:
Input: nums = [-1,-2,-3,0,1]
Output: 2
Explanation: The longest subarray with positive product is [-1,-2] or [-2,-3].
Example 4:
Input: nums = [-1,2]
Output: 1
Example 5:
Input: nums = [1,2,3,5,-6,4,0,10]
Output: 4
Constraints:
1 <= nums.length <= 10^5
-10^9 <= nums[i] <= 10^9
|
class Solution:
def getMaxLen(self, nums: List[int]) -> int:
res, pos, neg = 0, 0, 0
for num in nums:
if num == 0:
pos, neg = 0, 0
elif num > 0:
if neg != 0: neg, pos = neg+1, pos+1
else: neg, pos = 0, pos+1
else:
if neg != 0: pos, neg = neg+1, pos+1
else: neg, pos = pos+1, 0
res = max(res, pos)
return res
|
Given an array of integers nums, find the maximum length of a subarray where the product of all its elements is positive.
A subarray of an array is a consecutive sequence of zero or more values taken out of that array.
Return the maximum length of a subarray with positive product.
Example 1:
Input: nums = [1,-2,-3,4]
Output: 4
Explanation: The array nums already has a positive product of 24.
Example 2:
Input: nums = [0,1,-2,-3,-4]
Output: 3
Explanation: The longest subarray with positive product is [1,-2,-3] which has a product of 6.
Notice that we cannot include 0 in the subarray since that'll make the product 0 which is not positive.
Example 3:
Input: nums = [-1,-2,-3,0,1]
Output: 2
Explanation: The longest subarray with positive product is [-1,-2] or [-2,-3].
Example 4:
Input: nums = [-1,2]
Output: 1
Example 5:
Input: nums = [1,2,3,5,-6,4,0,10]
Output: 4
Constraints:
1 <= nums.length <= 10^5
-10^9 <= nums[i] <= 10^9
|
class Solution:
def getMaxLen(self, nums: List[int]) -> int:
ans=0
mn=0
mp=0
for i in nums:
if i==0:
mn,mp=0,0
elif i>0:
mp+=1
if mn!=0:
mn+=1
else:mn=0
else:
omn=mn
mn=mp+1
if omn!=0:
mp=omn+1
else:
mp=0
ans=max(mp,ans)
return ans
|
Given an array of integers nums, find the maximum length of a subarray where the product of all its elements is positive.
A subarray of an array is a consecutive sequence of zero or more values taken out of that array.
Return the maximum length of a subarray with positive product.
Example 1:
Input: nums = [1,-2,-3,4]
Output: 4
Explanation: The array nums already has a positive product of 24.
Example 2:
Input: nums = [0,1,-2,-3,-4]
Output: 3
Explanation: The longest subarray with positive product is [1,-2,-3] which has a product of 6.
Notice that we cannot include 0 in the subarray since that'll make the product 0 which is not positive.
Example 3:
Input: nums = [-1,-2,-3,0,1]
Output: 2
Explanation: The longest subarray with positive product is [-1,-2] or [-2,-3].
Example 4:
Input: nums = [-1,2]
Output: 1
Example 5:
Input: nums = [1,2,3,5,-6,4,0,10]
Output: 4
Constraints:
1 <= nums.length <= 10^5
-10^9 <= nums[i] <= 10^9
|
class Solution:
def getMaxLen(self, nums: List[int]) -> int:
# dp = [[0 for i in range(2)] for j in range(len(nums) + 1)]
# res = 0
# for i, num in enumerate(nums):
# if num == 0:
# dp[i + 1][0] = dp[i + 1][1] = 0
# elif num > 0:
# dp[i + 1][0] = dp[i][0] + 1
# dp[i + 1][1] = dp[i][1] + 1 if dp[i][1] else 0
# else:
# dp[i + 1][0] = dp[i][1] + 1 if dp[i][1] else 0
# dp[i + 1][1] = dp[i][0] + 1
# res = max(res, dp[i + 1][0])
# return res
pos_num = neg_num = res = 0
for i, num in enumerate(nums):
if num == 0:
pos_num = neg_num = 0
elif num > 0:
neg_num = neg_num + 1 if neg_num else 0
pos_num += 1
else:
cur_pos = pos_num
pos_num = neg_num + 1 if neg_num else 0
neg_num = cur_pos + 1
res = max(res, pos_num)
return res
|
Given an array of integers nums, find the maximum length of a subarray where the product of all its elements is positive.
A subarray of an array is a consecutive sequence of zero or more values taken out of that array.
Return the maximum length of a subarray with positive product.
Example 1:
Input: nums = [1,-2,-3,4]
Output: 4
Explanation: The array nums already has a positive product of 24.
Example 2:
Input: nums = [0,1,-2,-3,-4]
Output: 3
Explanation: The longest subarray with positive product is [1,-2,-3] which has a product of 6.
Notice that we cannot include 0 in the subarray since that'll make the product 0 which is not positive.
Example 3:
Input: nums = [-1,-2,-3,0,1]
Output: 2
Explanation: The longest subarray with positive product is [-1,-2] or [-2,-3].
Example 4:
Input: nums = [-1,2]
Output: 1
Example 5:
Input: nums = [1,2,3,5,-6,4,0,10]
Output: 4
Constraints:
1 <= nums.length <= 10^5
-10^9 <= nums[i] <= 10^9
|
class Solution:
def getMaxLen(self, nums: List[int]) -> int:
def helper(arr):
inds = []
for i,num in enumerate(arr):
if num<0:
inds.append(i)
if len(inds)%2==0:
return len(arr)
else:
first = max(inds[0],len(arr)-inds[0]-1)
second = max(inds[-1],len(arr)-inds[-1]-1)
return max(first,second)
temp = []
for i,num in enumerate(nums):
if num==0:
temp.append(i)
pos = []
if temp:
if nums[:temp[0]]:
pos.append(nums[:temp[0]])
for i in range(0,len(temp)-1):
pos.append(nums[temp[i]+1:temp[i+1]])
if nums[temp[-1]+1:]:
pos.append(nums[temp[-1]+1:])
else:
pos.append(nums)
ans = 0
for arr in pos:
ans = max(ans,helper(arr))
return ans
|
Given an array of integers nums, find the maximum length of a subarray where the product of all its elements is positive.
A subarray of an array is a consecutive sequence of zero or more values taken out of that array.
Return the maximum length of a subarray with positive product.
Example 1:
Input: nums = [1,-2,-3,4]
Output: 4
Explanation: The array nums already has a positive product of 24.
Example 2:
Input: nums = [0,1,-2,-3,-4]
Output: 3
Explanation: The longest subarray with positive product is [1,-2,-3] which has a product of 6.
Notice that we cannot include 0 in the subarray since that'll make the product 0 which is not positive.
Example 3:
Input: nums = [-1,-2,-3,0,1]
Output: 2
Explanation: The longest subarray with positive product is [-1,-2] or [-2,-3].
Example 4:
Input: nums = [-1,2]
Output: 1
Example 5:
Input: nums = [1,2,3,5,-6,4,0,10]
Output: 4
Constraints:
1 <= nums.length <= 10^5
-10^9 <= nums[i] <= 10^9
|
class Solution:
def getMaxLen(self, nums: List[int]) -> int:
lists = [[]]
negative = [[]]
index = 0
for num in nums:
if num == 0:
index = 0
negative.append([])
lists.append([])
else:
if num < 0:
negative[-1].append(index)
lists[-1].append(num)
index += 1
max_len = 0
for l, neg in zip(lists, negative):
if len(neg) % 2 == 1:
dist = min(neg[0] + 1, len(l) - neg[-1])
else:
dist = 0
max_len = max(len(l) - dist, max_len)
return max_len
|
Given an array of integers nums, find the maximum length of a subarray where the product of all its elements is positive.
A subarray of an array is a consecutive sequence of zero or more values taken out of that array.
Return the maximum length of a subarray with positive product.
Example 1:
Input: nums = [1,-2,-3,4]
Output: 4
Explanation: The array nums already has a positive product of 24.
Example 2:
Input: nums = [0,1,-2,-3,-4]
Output: 3
Explanation: The longest subarray with positive product is [1,-2,-3] which has a product of 6.
Notice that we cannot include 0 in the subarray since that'll make the product 0 which is not positive.
Example 3:
Input: nums = [-1,-2,-3,0,1]
Output: 2
Explanation: The longest subarray with positive product is [-1,-2] or [-2,-3].
Example 4:
Input: nums = [-1,2]
Output: 1
Example 5:
Input: nums = [1,2,3,5,-6,4,0,10]
Output: 4
Constraints:
1 <= nums.length <= 10^5
-10^9 <= nums[i] <= 10^9
|
import copy
import math
class Solution:
def getMaxLen(self, nums: List[int]) -> int:
positive,negative = 0,0
length = 0
for n in nums:
if n == 0:
positive,negative = 0,0
elif n > 0:
if negative > 0 : positive,negative = positive+1,negative+1
else: positive,negative = positive+1,0
else:
if negative > 0 : positive,negative = negative+1,positive+1
else: positive,negative = 0,positive+1
length = max(length,positive)
return length
|
Given an array of integers nums, find the maximum length of a subarray where the product of all its elements is positive.
A subarray of an array is a consecutive sequence of zero or more values taken out of that array.
Return the maximum length of a subarray with positive product.
Example 1:
Input: nums = [1,-2,-3,4]
Output: 4
Explanation: The array nums already has a positive product of 24.
Example 2:
Input: nums = [0,1,-2,-3,-4]
Output: 3
Explanation: The longest subarray with positive product is [1,-2,-3] which has a product of 6.
Notice that we cannot include 0 in the subarray since that'll make the product 0 which is not positive.
Example 3:
Input: nums = [-1,-2,-3,0,1]
Output: 2
Explanation: The longest subarray with positive product is [-1,-2] or [-2,-3].
Example 4:
Input: nums = [-1,2]
Output: 1
Example 5:
Input: nums = [1,2,3,5,-6,4,0,10]
Output: 4
Constraints:
1 <= nums.length <= 10^5
-10^9 <= nums[i] <= 10^9
|
import numpy as np
class Solution:
def getMaxLen(self, nums: List[int]) -> int:
if len(nums)==0: return (0)
if len(nums)==1:return( 1 if nums[0]>0 else 0)
St=[i for i,j in enumerate(nums) if (i==0 and j!=0) or (nums[i-1]==0 and j!=0)]
if len(St)==0: return (0)
Ed=[i for i,j in enumerate(nums) if (i==len(nums)-1 and j!=0) or (i<len(nums)-1 and nums[i+1]==0 and j!=0)]
# print(St,Ed)
Sta=np.array(St)
Eda=np.array(Ed)
Lns=(-(Eda-Sta+1)).argsort()
# print(Lns)
k=0
mxLen=0
while(k<len(Lns)):
nums1=nums[St[Lns[k]]:(Ed[Lns[k]]+1)]
if len(nums1)==mxLen: return(mxLen)
ni=[i for i,j in enumerate(nums1) if j<0]
if len(ni)==0 or len(ni)%2==0:mxLen=max(mxLen,len(nums1))
else:
mn=min(ni)
mx=max(ni)
mxLen= max(mxLen,mn,len(nums1)-mn-1,mx,len(nums1)-mx-1)
k=k+1
return(mxLen)
|
Given an array of integers nums, find the maximum length of a subarray where the product of all its elements is positive.
A subarray of an array is a consecutive sequence of zero or more values taken out of that array.
Return the maximum length of a subarray with positive product.
Example 1:
Input: nums = [1,-2,-3,4]
Output: 4
Explanation: The array nums already has a positive product of 24.
Example 2:
Input: nums = [0,1,-2,-3,-4]
Output: 3
Explanation: The longest subarray with positive product is [1,-2,-3] which has a product of 6.
Notice that we cannot include 0 in the subarray since that'll make the product 0 which is not positive.
Example 3:
Input: nums = [-1,-2,-3,0,1]
Output: 2
Explanation: The longest subarray with positive product is [-1,-2] or [-2,-3].
Example 4:
Input: nums = [-1,2]
Output: 1
Example 5:
Input: nums = [1,2,3,5,-6,4,0,10]
Output: 4
Constraints:
1 <= nums.length <= 10^5
-10^9 <= nums[i] <= 10^9
|
class Solution:
def getMaxLen(self, nums: List[int]) -> int:
p = 1
j = None
k = -1
m = 0
for i, n in enumerate(nums):
if not n:
p = 1
j = None
k = i
else:
if n < 0:
p *= -1
elif not n:
p = 0
if p > 0:
m = max(m, i-k)
elif p < 0:
if j is None:
j = i
else:
m = max(m, i-j)
return m
|
Given an array of integers nums, find the maximum length of a subarray where the product of all its elements is positive.
A subarray of an array is a consecutive sequence of zero or more values taken out of that array.
Return the maximum length of a subarray with positive product.
Example 1:
Input: nums = [1,-2,-3,4]
Output: 4
Explanation: The array nums already has a positive product of 24.
Example 2:
Input: nums = [0,1,-2,-3,-4]
Output: 3
Explanation: The longest subarray with positive product is [1,-2,-3] which has a product of 6.
Notice that we cannot include 0 in the subarray since that'll make the product 0 which is not positive.
Example 3:
Input: nums = [-1,-2,-3,0,1]
Output: 2
Explanation: The longest subarray with positive product is [-1,-2] or [-2,-3].
Example 4:
Input: nums = [-1,2]
Output: 1
Example 5:
Input: nums = [1,2,3,5,-6,4,0,10]
Output: 4
Constraints:
1 <= nums.length <= 10^5
-10^9 <= nums[i] <= 10^9
|
class Solution:
def getMaxLen(self, nums: List[int]) -> int:
# DP may be unnecessary, but because I saw max length subarray
# I assumed that it would be DP. Solution approach was DP-esque
# but it doesn't seem necessary.
# Seems like another way could be to just count the number of
# negatives (between 0s).
p = 0
n = 0
longest_p = 0
for num in nums:
longest_p = max(longest_p, p)
if num == 0:
p = 0
n = 0
elif num > 0:
prev_p = p
prev_n = n
p = prev_p + 1
if prev_n > 0:
n = prev_n + 1
else:
n = 0
elif num < 0:
prev_p = p
prev_n = n
n = prev_p + 1
if prev_n > 0:
p = prev_n + 1
else:
p = 0
longest_p = max(longest_p, p)
return longest_p
|
Given an array of integers nums, find the maximum length of a subarray where the product of all its elements is positive.
A subarray of an array is a consecutive sequence of zero or more values taken out of that array.
Return the maximum length of a subarray with positive product.
Example 1:
Input: nums = [1,-2,-3,4]
Output: 4
Explanation: The array nums already has a positive product of 24.
Example 2:
Input: nums = [0,1,-2,-3,-4]
Output: 3
Explanation: The longest subarray with positive product is [1,-2,-3] which has a product of 6.
Notice that we cannot include 0 in the subarray since that'll make the product 0 which is not positive.
Example 3:
Input: nums = [-1,-2,-3,0,1]
Output: 2
Explanation: The longest subarray with positive product is [-1,-2] or [-2,-3].
Example 4:
Input: nums = [-1,2]
Output: 1
Example 5:
Input: nums = [1,2,3,5,-6,4,0,10]
Output: 4
Constraints:
1 <= nums.length <= 10^5
-10^9 <= nums[i] <= 10^9
|
class Solution:
def getMaxLen(self, nums: List[int]) -> int:
n = len(nums)
if n == 1:
return 1 if nums[0] > 0 else 0
p1 = p2 = 0
answer = 0
curr_len = 0
neg_indx = deque([])
while p2 < n:
num = nums[p2]
if num == 0:
answer = max(answer, curr_len)
curr_len = 0
p2 += 1
p1 = p2
neg_indx = deque([])
elif num > 0:
curr_len += 1
answer = max(answer, curr_len)
p2 += 1
else:
neg_indx.append(p2)
j = p2+1
found = False
while j < n:
num2 = nums[j]
if num2 <= 0:
if num2 < 0:
neg_indx.append(j)
found = True
break
j += 1
if found:
curr_len += (j-p2+1)
answer = max(answer, curr_len)
if j == n-1:
return answer
else:
p2 = j + 1
else:
first_neg = neg_indx.popleft()
while p1 <= first_neg:
p1 += 1
curr_len -= 1
if p1 > p2:
p2 = p1
answer = max(answer, curr_len)
curr_len = 0
else:
curr_len += 1
p2 += 1
continue
return answer
#[1, -4, 3, 2, 0, 2, -2, 3, -2, -2, 3, 4, 5]
|
Given an array of integers nums, find the maximum length of a subarray where the product of all its elements is positive.
A subarray of an array is a consecutive sequence of zero or more values taken out of that array.
Return the maximum length of a subarray with positive product.
Example 1:
Input: nums = [1,-2,-3,4]
Output: 4
Explanation: The array nums already has a positive product of 24.
Example 2:
Input: nums = [0,1,-2,-3,-4]
Output: 3
Explanation: The longest subarray with positive product is [1,-2,-3] which has a product of 6.
Notice that we cannot include 0 in the subarray since that'll make the product 0 which is not positive.
Example 3:
Input: nums = [-1,-2,-3,0,1]
Output: 2
Explanation: The longest subarray with positive product is [-1,-2] or [-2,-3].
Example 4:
Input: nums = [-1,2]
Output: 1
Example 5:
Input: nums = [1,2,3,5,-6,4,0,10]
Output: 4
Constraints:
1 <= nums.length <= 10^5
-10^9 <= nums[i] <= 10^9
|
class Solution:
def getMaxLen(self, nums):
if len(nums) == 0:
return True
result = 0
count = 0
zero_marker = -1
negative_marker = -1
for i in range(len(nums)):
if nums[i] == 0:
zero_marker = i
count = 0
negative_marker = -1
else:
if nums[i] < 0:
count += 1
if negative_marker == -1:
negative_marker = i
if count % 2 == 0:
result = max(result, i - zero_marker)
else:
result = max(result, i - negative_marker)
return result
|
Given an array of integers nums, find the maximum length of a subarray where the product of all its elements is positive.
A subarray of an array is a consecutive sequence of zero or more values taken out of that array.
Return the maximum length of a subarray with positive product.
Example 1:
Input: nums = [1,-2,-3,4]
Output: 4
Explanation: The array nums already has a positive product of 24.
Example 2:
Input: nums = [0,1,-2,-3,-4]
Output: 3
Explanation: The longest subarray with positive product is [1,-2,-3] which has a product of 6.
Notice that we cannot include 0 in the subarray since that'll make the product 0 which is not positive.
Example 3:
Input: nums = [-1,-2,-3,0,1]
Output: 2
Explanation: The longest subarray with positive product is [-1,-2] or [-2,-3].
Example 4:
Input: nums = [-1,2]
Output: 1
Example 5:
Input: nums = [1,2,3,5,-6,4,0,10]
Output: 4
Constraints:
1 <= nums.length <= 10^5
-10^9 <= nums[i] <= 10^9
|
class Solution:
def getMaxLen(self, nums: List[int]) -> int:
neg = pos = res = 0
for n in nums:
if n == 0:
neg = pos = 0
elif n > 0:
if neg:
neg += 1
pos += 1
else:
pos, neg = neg + 1 if neg else 0, pos + 1
res = max(res, pos)
return res
|
Given an array of integers nums, find the maximum length of a subarray where the product of all its elements is positive.
A subarray of an array is a consecutive sequence of zero or more values taken out of that array.
Return the maximum length of a subarray with positive product.
Example 1:
Input: nums = [1,-2,-3,4]
Output: 4
Explanation: The array nums already has a positive product of 24.
Example 2:
Input: nums = [0,1,-2,-3,-4]
Output: 3
Explanation: The longest subarray with positive product is [1,-2,-3] which has a product of 6.
Notice that we cannot include 0 in the subarray since that'll make the product 0 which is not positive.
Example 3:
Input: nums = [-1,-2,-3,0,1]
Output: 2
Explanation: The longest subarray with positive product is [-1,-2] or [-2,-3].
Example 4:
Input: nums = [-1,2]
Output: 1
Example 5:
Input: nums = [1,2,3,5,-6,4,0,10]
Output: 4
Constraints:
1 <= nums.length <= 10^5
-10^9 <= nums[i] <= 10^9
|
class Solution:
def getMaxLen(self, nums: List[int]) -> int:
n = len(nums)
def get_val(nums):
# print(nums)
if len(nums) == 0:
return 0
products = [1]
product = 1
length = len(nums)
for i in range(length):
product *= nums[i]
products.append(product)
for j in range(length, 0, -1):
for k in range(length-j+1):
value = products[k+j]//products[k]
if value>0:
return j
return 0
index = 0
maximum = 0
for i in range(n):
if nums[i] == 0:
if i == index:
index += 1
continue
value = get_val(nums[index:i])
if value>maximum:
maximum = value
index = i+1
elif nums[i]>0:
nums[i] = 1
else:
nums[i] = -1
value = get_val(nums[index:n])
if value>maximum:
maximum = value
return maximum
|
Given an array of integers nums, find the maximum length of a subarray where the product of all its elements is positive.
A subarray of an array is a consecutive sequence of zero or more values taken out of that array.
Return the maximum length of a subarray with positive product.
Example 1:
Input: nums = [1,-2,-3,4]
Output: 4
Explanation: The array nums already has a positive product of 24.
Example 2:
Input: nums = [0,1,-2,-3,-4]
Output: 3
Explanation: The longest subarray with positive product is [1,-2,-3] which has a product of 6.
Notice that we cannot include 0 in the subarray since that'll make the product 0 which is not positive.
Example 3:
Input: nums = [-1,-2,-3,0,1]
Output: 2
Explanation: The longest subarray with positive product is [-1,-2] or [-2,-3].
Example 4:
Input: nums = [-1,2]
Output: 1
Example 5:
Input: nums = [1,2,3,5,-6,4,0,10]
Output: 4
Constraints:
1 <= nums.length <= 10^5
-10^9 <= nums[i] <= 10^9
|
class Solution:
def getMaxLen(self, nums: List[int]) -> int:
maxl = 0
pos = 0
neg = 0
for n in nums:
if n == 0:
pos, neg = 0, 0
elif n > 0:
pos += 1
neg = neg + 1 if neg != 0 else 0
elif n < 0:
oldneg = neg
neg = pos + 1
pos = oldneg + 1 if oldneg > 0 else 0
maxl = max(maxl, pos)
return maxl
|
Given an array of integers nums, find the maximum length of a subarray where the product of all its elements is positive.
A subarray of an array is a consecutive sequence of zero or more values taken out of that array.
Return the maximum length of a subarray with positive product.
Example 1:
Input: nums = [1,-2,-3,4]
Output: 4
Explanation: The array nums already has a positive product of 24.
Example 2:
Input: nums = [0,1,-2,-3,-4]
Output: 3
Explanation: The longest subarray with positive product is [1,-2,-3] which has a product of 6.
Notice that we cannot include 0 in the subarray since that'll make the product 0 which is not positive.
Example 3:
Input: nums = [-1,-2,-3,0,1]
Output: 2
Explanation: The longest subarray with positive product is [-1,-2] or [-2,-3].
Example 4:
Input: nums = [-1,2]
Output: 1
Example 5:
Input: nums = [1,2,3,5,-6,4,0,10]
Output: 4
Constraints:
1 <= nums.length <= 10^5
-10^9 <= nums[i] <= 10^9
|
class Solution:
def getMaxLen(self, nums: List[int]) -> int:
def oddMinus(ls):
ret = 0
for i in range(len(ls)):
if ls[i] < 0:
ret = max(max(ret, i), len(ls)-1-i)
return ret
def getLen(ls):
minus = 0
for i in ls:
if i < 0:
minus += 1
if(minus % 2 == 0):
return len(ls)
else:
return oddMinus(ls)
s = []
sub = []
for i in nums:
if i == 0:
s.append(sub)
sub = []
else:
sub.append(i)
s.append(sub)
res = 0
for ls in s:
res = max(res, getLen(ls))
return res
|
Given an array of integers nums, find the maximum length of a subarray where the product of all its elements is positive.
A subarray of an array is a consecutive sequence of zero or more values taken out of that array.
Return the maximum length of a subarray with positive product.
Example 1:
Input: nums = [1,-2,-3,4]
Output: 4
Explanation: The array nums already has a positive product of 24.
Example 2:
Input: nums = [0,1,-2,-3,-4]
Output: 3
Explanation: The longest subarray with positive product is [1,-2,-3] which has a product of 6.
Notice that we cannot include 0 in the subarray since that'll make the product 0 which is not positive.
Example 3:
Input: nums = [-1,-2,-3,0,1]
Output: 2
Explanation: The longest subarray with positive product is [-1,-2] or [-2,-3].
Example 4:
Input: nums = [-1,2]
Output: 1
Example 5:
Input: nums = [1,2,3,5,-6,4,0,10]
Output: 4
Constraints:
1 <= nums.length <= 10^5
-10^9 <= nums[i] <= 10^9
|
class Solution:
def getMaxLen(self, nums: List[int]) -> int:
l = []
neg = []
index = 0
max_len = 0
for num in nums:
if num == 0:
index = 0
if len(neg) % 2 == 1:
dist = min(neg[0] + 1, len(l) - neg[-1])
else:
dist = 0
max_len = max(len(l) - dist, max_len)
l.clear()
neg.clear()
else:
if num < 0:
neg.append(index)
l.append(num)
index += 1
if len(neg) % 2 == 1:
dist = min(neg[0] + 1, len(l) - neg[-1])
else:
dist = 0
max_len = max(len(l) - dist, max_len)
return max_len
|
Given an array of integers nums, find the maximum length of a subarray where the product of all its elements is positive.
A subarray of an array is a consecutive sequence of zero or more values taken out of that array.
Return the maximum length of a subarray with positive product.
Example 1:
Input: nums = [1,-2,-3,4]
Output: 4
Explanation: The array nums already has a positive product of 24.
Example 2:
Input: nums = [0,1,-2,-3,-4]
Output: 3
Explanation: The longest subarray with positive product is [1,-2,-3] which has a product of 6.
Notice that we cannot include 0 in the subarray since that'll make the product 0 which is not positive.
Example 3:
Input: nums = [-1,-2,-3,0,1]
Output: 2
Explanation: The longest subarray with positive product is [-1,-2] or [-2,-3].
Example 4:
Input: nums = [-1,2]
Output: 1
Example 5:
Input: nums = [1,2,3,5,-6,4,0,10]
Output: 4
Constraints:
1 <= nums.length <= 10^5
-10^9 <= nums[i] <= 10^9
|
class Solution:
def getMaxLen(self, nums: List[int]) -> int:
n = len(nums)
pos, neg = [0] * n, [0] * n
if nums[0] > 0: pos[0] = 1
if nums[0] < 0: neg[0] = 1
ans = pos[0]
for i in range(1, n):
if nums[i] > 0:
pos[i] = 1 + pos[i - 1]
neg[i] = 1 + neg[i - 1] if neg[i - 1] > 0 else 0
elif nums[i] < 0:
pos[i] = 1 + neg[i - 1] if neg[i - 1] > 0 else 0
neg[i] = 1 + pos[i - 1]
ans = max(ans, pos[i])
return ans
|
Given an array of integers nums, find the maximum length of a subarray where the product of all its elements is positive.
A subarray of an array is a consecutive sequence of zero or more values taken out of that array.
Return the maximum length of a subarray with positive product.
Example 1:
Input: nums = [1,-2,-3,4]
Output: 4
Explanation: The array nums already has a positive product of 24.
Example 2:
Input: nums = [0,1,-2,-3,-4]
Output: 3
Explanation: The longest subarray with positive product is [1,-2,-3] which has a product of 6.
Notice that we cannot include 0 in the subarray since that'll make the product 0 which is not positive.
Example 3:
Input: nums = [-1,-2,-3,0,1]
Output: 2
Explanation: The longest subarray with positive product is [-1,-2] or [-2,-3].
Example 4:
Input: nums = [-1,2]
Output: 1
Example 5:
Input: nums = [1,2,3,5,-6,4,0,10]
Output: 4
Constraints:
1 <= nums.length <= 10^5
-10^9 <= nums[i] <= 10^9
|
class Solution:
def getMaxLen(self, nums: List[int]) -> int:
ret = 0
pos, neg = -1, None
curr = 0
for i, n in enumerate(nums):
if n == 0:
pos, neg = i, None
curr = 0
else:
if n < 0:
curr = 1 - curr
if curr == 0:
ret = max(ret, i - pos)
if curr == 1:
if neg is not None:
ret = max(ret, i - neg)
else:
neg = i
return ret
|
Given an array of integers nums, find the maximum length of a subarray where the product of all its elements is positive.
A subarray of an array is a consecutive sequence of zero or more values taken out of that array.
Return the maximum length of a subarray with positive product.
Example 1:
Input: nums = [1,-2,-3,4]
Output: 4
Explanation: The array nums already has a positive product of 24.
Example 2:
Input: nums = [0,1,-2,-3,-4]
Output: 3
Explanation: The longest subarray with positive product is [1,-2,-3] which has a product of 6.
Notice that we cannot include 0 in the subarray since that'll make the product 0 which is not positive.
Example 3:
Input: nums = [-1,-2,-3,0,1]
Output: 2
Explanation: The longest subarray with positive product is [-1,-2] or [-2,-3].
Example 4:
Input: nums = [-1,2]
Output: 1
Example 5:
Input: nums = [1,2,3,5,-6,4,0,10]
Output: 4
Constraints:
1 <= nums.length <= 10^5
-10^9 <= nums[i] <= 10^9
|
class Solution:
def getMaxLen(self, nums: List[int]) -> int:
nums.append(0)
start = -1
i = 0
firstn = -1
maxl = 0
nneg = 0
while i<len(nums):
if nums[i]<0:
nneg += 1
if firstn<0: firstn = i
lastn = i
elif nums[i] == 0:
if nneg%2 == 0:
maxl = max(maxl,i-start-1)
else:
maxl = max([maxl,lastn-start-1,i-firstn-1])
start = i
nneg = 0
firstn = -1
i += 1
return maxl
|
Given an array of integers nums, find the maximum length of a subarray where the product of all its elements is positive.
A subarray of an array is a consecutive sequence of zero or more values taken out of that array.
Return the maximum length of a subarray with positive product.
Example 1:
Input: nums = [1,-2,-3,4]
Output: 4
Explanation: The array nums already has a positive product of 24.
Example 2:
Input: nums = [0,1,-2,-3,-4]
Output: 3
Explanation: The longest subarray with positive product is [1,-2,-3] which has a product of 6.
Notice that we cannot include 0 in the subarray since that'll make the product 0 which is not positive.
Example 3:
Input: nums = [-1,-2,-3,0,1]
Output: 2
Explanation: The longest subarray with positive product is [-1,-2] or [-2,-3].
Example 4:
Input: nums = [-1,2]
Output: 1
Example 5:
Input: nums = [1,2,3,5,-6,4,0,10]
Output: 4
Constraints:
1 <= nums.length <= 10^5
-10^9 <= nums[i] <= 10^9
|
class Solution:
def getMaxLen(self, nums: List[int]) -> int:
n = len(nums)
pos, neg = [0] * n, [0] * n
if nums[0] > 0: pos[0] = 1
if nums[0] < 0: neg[0] = 1
ans = pos[0]
for i in range(1, n):
if nums[i] > 0:
pos[i] = 1 + pos[i - 1]
neg[i] = 1 + neg[i - 1] if neg[i - 1] > 0 else 0
elif nums[i] < 0:
pos[i] = 1 + neg[i - 1] if neg[i - 1] > 0 else 0
neg[i] = 1 + pos[i - 1]
ans = max(ans, pos[i])
return ans
|
Given an array of integers nums, find the maximum length of a subarray where the product of all its elements is positive.
A subarray of an array is a consecutive sequence of zero or more values taken out of that array.
Return the maximum length of a subarray with positive product.
Example 1:
Input: nums = [1,-2,-3,4]
Output: 4
Explanation: The array nums already has a positive product of 24.
Example 2:
Input: nums = [0,1,-2,-3,-4]
Output: 3
Explanation: The longest subarray with positive product is [1,-2,-3] which has a product of 6.
Notice that we cannot include 0 in the subarray since that'll make the product 0 which is not positive.
Example 3:
Input: nums = [-1,-2,-3,0,1]
Output: 2
Explanation: The longest subarray with positive product is [-1,-2] or [-2,-3].
Example 4:
Input: nums = [-1,2]
Output: 1
Example 5:
Input: nums = [1,2,3,5,-6,4,0,10]
Output: 4
Constraints:
1 <= nums.length <= 10^5
-10^9 <= nums[i] <= 10^9
|
class Solution:
def getMaxLen(self, nums: List[int]) -> int:
def dfs(start):
i = start
if i >= len(nums):
return 0
ret = 0
stack = []
while i < len(nums):
if nums[i] == 0:
break
elif nums[i] < 0:
stack.append(i)
i+=1
if len(stack) % 2 == 0:
ret = i - start
else:
ret = max(i-1-stack[0],stack[-1]-start)
return max(ret,dfs(i+1))
return dfs(0)
|
Given an array of integers nums, find the maximum length of a subarray where the product of all its elements is positive.
A subarray of an array is a consecutive sequence of zero or more values taken out of that array.
Return the maximum length of a subarray with positive product.
Example 1:
Input: nums = [1,-2,-3,4]
Output: 4
Explanation: The array nums already has a positive product of 24.
Example 2:
Input: nums = [0,1,-2,-3,-4]
Output: 3
Explanation: The longest subarray with positive product is [1,-2,-3] which has a product of 6.
Notice that we cannot include 0 in the subarray since that'll make the product 0 which is not positive.
Example 3:
Input: nums = [-1,-2,-3,0,1]
Output: 2
Explanation: The longest subarray with positive product is [-1,-2] or [-2,-3].
Example 4:
Input: nums = [-1,2]
Output: 1
Example 5:
Input: nums = [1,2,3,5,-6,4,0,10]
Output: 4
Constraints:
1 <= nums.length <= 10^5
-10^9 <= nums[i] <= 10^9
|
class Solution:
def getMaxLen(self, nums: List[int]) -> int:
def solve(arr):
maxy = 0
count = 0
for i in j:
if i < 0:
count += 1
if count % 2 == 0:
maxy = max(maxy,len(j))
else:
for i in range(len(j)):
if j[i] < 0:
m1 = i
m2 = len(j) - m1 -1
m3 = max(m1,m2)
maxy = max(maxy,m3)
break
for i in range(len(j)-1,-1,-1):
if j[i] < 0:
m1 = i
m2 = len(j) - m1 - 1
m3 = max(m1,m2)
maxy = max(maxy,m3)
break
return maxy
res = []
maxy = 0
flag = 1
i = 0
for j in range(i,len(nums)):
if nums[j] == 0:
res.append(nums[i:j])
i = j+1
flag = 0
if flag == 1:
res.append(nums)
elif flag == 0:
res.append(nums[i:])
nums = res
for j in nums:
maxy = max(maxy,solve(j))
return maxy
|
Given an array of integers nums, find the maximum length of a subarray where the product of all its elements is positive.
A subarray of an array is a consecutive sequence of zero or more values taken out of that array.
Return the maximum length of a subarray with positive product.
Example 1:
Input: nums = [1,-2,-3,4]
Output: 4
Explanation: The array nums already has a positive product of 24.
Example 2:
Input: nums = [0,1,-2,-3,-4]
Output: 3
Explanation: The longest subarray with positive product is [1,-2,-3] which has a product of 6.
Notice that we cannot include 0 in the subarray since that'll make the product 0 which is not positive.
Example 3:
Input: nums = [-1,-2,-3,0,1]
Output: 2
Explanation: The longest subarray with positive product is [-1,-2] or [-2,-3].
Example 4:
Input: nums = [-1,2]
Output: 1
Example 5:
Input: nums = [1,2,3,5,-6,4,0,10]
Output: 4
Constraints:
1 <= nums.length <= 10^5
-10^9 <= nums[i] <= 10^9
|
class Solution:
def getMaxLen(self, nums: List[int]) -> int:
firstNeg = -1
zeroPos = -1
cnt = 0
ret = 0
for i, n in enumerate(nums):
if n < 0:
cnt += 1
if firstNeg == -1:
firstNeg = i
elif not n:
firstNeg, cnt = -1, 0
zeroPos = i
if cnt % 2:
ret = max(ret, i - firstNeg)
else:
ret = max(ret, i - zeroPos)
return ret
|
Given an array of integers nums, find the maximum length of a subarray where the product of all its elements is positive.
A subarray of an array is a consecutive sequence of zero or more values taken out of that array.
Return the maximum length of a subarray with positive product.
Example 1:
Input: nums = [1,-2,-3,4]
Output: 4
Explanation: The array nums already has a positive product of 24.
Example 2:
Input: nums = [0,1,-2,-3,-4]
Output: 3
Explanation: The longest subarray with positive product is [1,-2,-3] which has a product of 6.
Notice that we cannot include 0 in the subarray since that'll make the product 0 which is not positive.
Example 3:
Input: nums = [-1,-2,-3,0,1]
Output: 2
Explanation: The longest subarray with positive product is [-1,-2] or [-2,-3].
Example 4:
Input: nums = [-1,2]
Output: 1
Example 5:
Input: nums = [1,2,3,5,-6,4,0,10]
Output: 4
Constraints:
1 <= nums.length <= 10^5
-10^9 <= nums[i] <= 10^9
|
class Solution:
def getMaxLen(self, nums: List[int]) -> int:
pos = neg = max_len = 0
for n in nums:
if n > 0:
neg = (1 + neg) if neg > 0 else 0
pos = (1 + pos)
elif n < 0:
#n1 = neg
#neg = (1 + pos)
pos, neg = (1 + neg) if neg > 0 else 0, 1+pos
else:
pos = neg = 0
max_len = max(max_len, pos)
return max_len
|
Given an array of integers nums, find the maximum length of a subarray where the product of all its elements is positive.
A subarray of an array is a consecutive sequence of zero or more values taken out of that array.
Return the maximum length of a subarray with positive product.
Example 1:
Input: nums = [1,-2,-3,4]
Output: 4
Explanation: The array nums already has a positive product of 24.
Example 2:
Input: nums = [0,1,-2,-3,-4]
Output: 3
Explanation: The longest subarray with positive product is [1,-2,-3] which has a product of 6.
Notice that we cannot include 0 in the subarray since that'll make the product 0 which is not positive.
Example 3:
Input: nums = [-1,-2,-3,0,1]
Output: 2
Explanation: The longest subarray with positive product is [-1,-2] or [-2,-3].
Example 4:
Input: nums = [-1,2]
Output: 1
Example 5:
Input: nums = [1,2,3,5,-6,4,0,10]
Output: 4
Constraints:
1 <= nums.length <= 10^5
-10^9 <= nums[i] <= 10^9
|
class Solution:
def getMaxLen(self, arr: List[int]) -> int:
i=0
while i<=len(arr)-1 and arr[i]==0:
i+=1
arr=arr[i:]
if len(arr)==0:
return 0
i=len(arr)-1
while i<=len(arr)-1 and arr[i]==0:
i-=1
arr=arr[:i+1]
if len(arr)==0:
return 0
array=[]
low=0
high=0
ans=[]
while low <len(arr):
while high<len(arr) and arr[high] != 0:
high+=1
if high == len(arr)-1:
break
else:
array.append(arr[low:high])
while high<len(arr) and arr[high]==0:
high+=1
low=high
for a in array:
if len(a)==0:
continue
else:
total=0
first=0
last=0
for i in range(len(a)):
if a[i]<0:
total+=1
if total%2==0:
ans.append(len(a))
else:
i=0
while a[i]>0:
i+=1
first=len(a)-(i+1)
i=len(a)-1
while a[i]>0:
i-=1
last=i
ans.append(max(first,last))
ma=0
for i in ans:
if i>ma:
ma=i
return ma
|
Given an array of integers nums, find the maximum length of a subarray where the product of all its elements is positive.
A subarray of an array is a consecutive sequence of zero or more values taken out of that array.
Return the maximum length of a subarray with positive product.
Example 1:
Input: nums = [1,-2,-3,4]
Output: 4
Explanation: The array nums already has a positive product of 24.
Example 2:
Input: nums = [0,1,-2,-3,-4]
Output: 3
Explanation: The longest subarray with positive product is [1,-2,-3] which has a product of 6.
Notice that we cannot include 0 in the subarray since that'll make the product 0 which is not positive.
Example 3:
Input: nums = [-1,-2,-3,0,1]
Output: 2
Explanation: The longest subarray with positive product is [-1,-2] or [-2,-3].
Example 4:
Input: nums = [-1,2]
Output: 1
Example 5:
Input: nums = [1,2,3,5,-6,4,0,10]
Output: 4
Constraints:
1 <= nums.length <= 10^5
-10^9 <= nums[i] <= 10^9
|
class Solution:
def getMaxLen(self, nums: List[int]) -> int:
out = 0
first = -1
last = -1
negs = 0
start = 0
for i,num in enumerate(nums):
if num == 0:
if negs % 2 == 0:
new_max = i-start
else:
new_max = max(i-first-1,last-start)
out = max(out,new_max)
first = -1
last = -1
negs = 0
start = i+1
if num < 0:
negs += 1
if first == -1:
first = i
last = i
i+=1
if negs % 2 == 0:
new_max = i-start
else:
new_max = max(i-first-1,last-start)
out = max(out,new_max)
return out
|
Given an array of integers nums, find the maximum length of a subarray where the product of all its elements is positive.
A subarray of an array is a consecutive sequence of zero or more values taken out of that array.
Return the maximum length of a subarray with positive product.
Example 1:
Input: nums = [1,-2,-3,4]
Output: 4
Explanation: The array nums already has a positive product of 24.
Example 2:
Input: nums = [0,1,-2,-3,-4]
Output: 3
Explanation: The longest subarray with positive product is [1,-2,-3] which has a product of 6.
Notice that we cannot include 0 in the subarray since that'll make the product 0 which is not positive.
Example 3:
Input: nums = [-1,-2,-3,0,1]
Output: 2
Explanation: The longest subarray with positive product is [-1,-2] or [-2,-3].
Example 4:
Input: nums = [-1,2]
Output: 1
Example 5:
Input: nums = [1,2,3,5,-6,4,0,10]
Output: 4
Constraints:
1 <= nums.length <= 10^5
-10^9 <= nums[i] <= 10^9
|
class Solution:
def getMaxLen(self, nums: List[int]) -> int:
dp = [[0 for i in range(2)] for j in range(len(nums) + 1)]
res = 0
for i, num in enumerate(nums):
if num == 0:
dp[i + 1][0] = dp[num][1] = 0
elif num > 0:
dp[i + 1][0] = dp[i][0] + 1
dp[i + 1][1] = dp[i][1] + 1 if dp[i][1] else 0
else:
dp[i + 1][0] = dp[i][1] + 1 if dp[i][1] else 0
dp[i + 1][1] = dp[i][0] + 1
res = max(res, dp[i + 1][0])
return res
|
Given an array of integers nums, find the maximum length of a subarray where the product of all its elements is positive.
A subarray of an array is a consecutive sequence of zero or more values taken out of that array.
Return the maximum length of a subarray with positive product.
Example 1:
Input: nums = [1,-2,-3,4]
Output: 4
Explanation: The array nums already has a positive product of 24.
Example 2:
Input: nums = [0,1,-2,-3,-4]
Output: 3
Explanation: The longest subarray with positive product is [1,-2,-3] which has a product of 6.
Notice that we cannot include 0 in the subarray since that'll make the product 0 which is not positive.
Example 3:
Input: nums = [-1,-2,-3,0,1]
Output: 2
Explanation: The longest subarray with positive product is [-1,-2] or [-2,-3].
Example 4:
Input: nums = [-1,2]
Output: 1
Example 5:
Input: nums = [1,2,3,5,-6,4,0,10]
Output: 4
Constraints:
1 <= nums.length <= 10^5
-10^9 <= nums[i] <= 10^9
|
class Solution:
def getMaxLen(self, nums: List[int]) -> int:
ans = 0
neg = 0
lo, hi = 0, -1
for i, num in enumerate(nums):
if num == 0:
lo = i+1
neg = 0
elif num < 0:
neg += 1
hi = i
if neg % 2 == 0:
#print(lo,hi)
ans = max(ans, hi - lo + 1)
neg = 0
nums = nums[::-1]
lo, hi = 0, -1
for i, num in enumerate(nums):
if num == 0:
lo = i+1
neg = 0
elif num < 0:
neg += 1
hi = i
if neg % 2 == 0:
#print(lo,hi)
ans = max(ans, hi - lo + 1)
return ans
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.