inputs
stringlengths 50
14k
| targets
stringlengths 4
655k
|
|---|---|
A sequence X_1, X_2, ..., X_n is fibonacci-like if:
n >= 3
X_i + X_{i+1} = X_{i+2} for all i + 2 <= n
Given a strictly increasing array A of positive integers forming a sequence, find the length of the longest fibonacci-like subsequence of A. If one does not exist, return 0.
(Recall that a subsequence is derived from another sequence A by deleting any number of elements (including none) from A, without changing the order of the remaining elements. For example, [3, 5, 8] is a subsequence of [3, 4, 5, 6, 7, 8].)
Example 1:
Input: [1,2,3,4,5,6,7,8]
Output: 5
Explanation:
The longest subsequence that is fibonacci-like: [1,2,3,5,8].
Example 2:
Input: [1,3,7,11,12,14,18]
Output: 3
Explanation:
The longest subsequence that is fibonacci-like:
[1,11,12], [3,11,14] or [7,11,18].
Note:
3 <= A.length <= 1000
1 <= A[0] < A[1] < ... < A[A.length - 1] <= 10^9
(The time limit has been reduced by 50% for submissions in Java, C, and C++.)
|
class Solution:
def lenLongestFibSubseq(self, A: List[int]) -> int:
table = {x:i for i,x in enumerate(A)}
longest = collections.defaultdict(lambda: 2)
result = 0
for k, a in enumerate(A):
for j in range(k):
i = table.get(a-A[j], None)
if i!=None and i<j:
longest[j, k] = longest[i, j] + 1
if longest[j, k] > result: result = longest[j,k]
return result if result>=3 else 0
|
A sequence X_1, X_2, ..., X_n is fibonacci-like if:
n >= 3
X_i + X_{i+1} = X_{i+2} for all i + 2 <= n
Given a strictly increasing array A of positive integers forming a sequence, find the length of the longest fibonacci-like subsequence of A. If one does not exist, return 0.
(Recall that a subsequence is derived from another sequence A by deleting any number of elements (including none) from A, without changing the order of the remaining elements. For example, [3, 5, 8] is a subsequence of [3, 4, 5, 6, 7, 8].)
Example 1:
Input: [1,2,3,4,5,6,7,8]
Output: 5
Explanation:
The longest subsequence that is fibonacci-like: [1,2,3,5,8].
Example 2:
Input: [1,3,7,11,12,14,18]
Output: 3
Explanation:
The longest subsequence that is fibonacci-like:
[1,11,12], [3,11,14] or [7,11,18].
Note:
3 <= A.length <= 1000
1 <= A[0] < A[1] < ... < A[A.length - 1] <= 10^9
(The time limit has been reduced by 50% for submissions in Java, C, and C++.)
|
class Solution:
def lenLongestFibSubseq(self, A: List[int]) -> int:
index = {x: i for i, x in enumerate(A)}
longest = collections.defaultdict(lambda: 2)
ans=0
for k,z in enumerate(A):
for j in range(k):
i=index.get(z-A[j],None)
if i!=None and i<j:
cand=longest[j,k]=longest[i,j]+1
ans=max(ans,cand)
return ans if ans>=3 else 0
|
A sequence X_1, X_2, ..., X_n is fibonacci-like if:
n >= 3
X_i + X_{i+1} = X_{i+2} for all i + 2 <= n
Given a strictly increasing array A of positive integers forming a sequence, find the length of the longest fibonacci-like subsequence of A. If one does not exist, return 0.
(Recall that a subsequence is derived from another sequence A by deleting any number of elements (including none) from A, without changing the order of the remaining elements. For example, [3, 5, 8] is a subsequence of [3, 4, 5, 6, 7, 8].)
Example 1:
Input: [1,2,3,4,5,6,7,8]
Output: 5
Explanation:
The longest subsequence that is fibonacci-like: [1,2,3,5,8].
Example 2:
Input: [1,3,7,11,12,14,18]
Output: 3
Explanation:
The longest subsequence that is fibonacci-like:
[1,11,12], [3,11,14] or [7,11,18].
Note:
3 <= A.length <= 1000
1 <= A[0] < A[1] < ... < A[A.length - 1] <= 10^9
(The time limit has been reduced by 50% for submissions in Java, C, and C++.)
|
class Solution:
def lenLongestFibSubseq(self, A):
sA = set(A)
last = A[-1]
B = Counter()
best = 0
for i in reversed(range(len(A))):
a = A[i]
for b in A[i+1:]:
c = a+b
if c in sA:
B[a,b] = 1 + B[b,c]
best = max(best , B[a,b]+2)
elif c>last:
break
return best
|
A sequence X_1, X_2, ..., X_n is fibonacci-like if:
n >= 3
X_i + X_{i+1} = X_{i+2} for all i + 2 <= n
Given a strictly increasing array A of positive integers forming a sequence, find the length of the longest fibonacci-like subsequence of A. If one does not exist, return 0.
(Recall that a subsequence is derived from another sequence A by deleting any number of elements (including none) from A, without changing the order of the remaining elements. For example, [3, 5, 8] is a subsequence of [3, 4, 5, 6, 7, 8].)
Example 1:
Input: [1,2,3,4,5,6,7,8]
Output: 5
Explanation:
The longest subsequence that is fibonacci-like: [1,2,3,5,8].
Example 2:
Input: [1,3,7,11,12,14,18]
Output: 3
Explanation:
The longest subsequence that is fibonacci-like:
[1,11,12], [3,11,14] or [7,11,18].
Note:
3 <= A.length <= 1000
1 <= A[0] < A[1] < ... < A[A.length - 1] <= 10^9
(The time limit has been reduced by 50% for submissions in Java, C, and C++.)
|
class Solution:
def lenLongestFibSubseq(self, A: List[int]) -> int:
dp = collections.defaultdict(int)
s =set(A)
n = len(A)
ans = 2
for j in range(n):
for i in range(j):
prev = A[j]-A[i]
if prev < A[i] and prev in s:
dp[A[i],A[j]] = dp.get((prev,A[i]),2) + 1
# ans = max(ans,dp[A[j],A[i]])
return max(list(dp.values()) or [0])
# dp = collections.defaultdict(int)
# s = set(A)
# for j in range(len(A)):
# for i in range(j):
# if A[j] - A[i] < A[i] and A[j] - A[i] in s:
# dp[A[i], A[j]] = dp.get((A[j] - A[i], A[i]), 2) + 1
# return max(dp.values() or [0])
|
A sequence X_1, X_2, ..., X_n is fibonacci-like if:
n >= 3
X_i + X_{i+1} = X_{i+2} for all i + 2 <= n
Given a strictly increasing array A of positive integers forming a sequence, find the length of the longest fibonacci-like subsequence of A. If one does not exist, return 0.
(Recall that a subsequence is derived from another sequence A by deleting any number of elements (including none) from A, without changing the order of the remaining elements. For example, [3, 5, 8] is a subsequence of [3, 4, 5, 6, 7, 8].)
Example 1:
Input: [1,2,3,4,5,6,7,8]
Output: 5
Explanation:
The longest subsequence that is fibonacci-like: [1,2,3,5,8].
Example 2:
Input: [1,3,7,11,12,14,18]
Output: 3
Explanation:
The longest subsequence that is fibonacci-like:
[1,11,12], [3,11,14] or [7,11,18].
Note:
3 <= A.length <= 1000
1 <= A[0] < A[1] < ... < A[A.length - 1] <= 10^9
(The time limit has been reduced by 50% for submissions in Java, C, and C++.)
|
class Solution:
def lenLongestFibSubseq(self, A: List[int]) -> int:
# # straight forward N^2log(N)
# n = len(A)
# s = set()
# for i in A:
# s.add(i)
# res = 0
# ll = 0
# for i in range(n):
# for j in range(i+1,n):
# f1 = A[i]
# f2 = A[j]
# if f1+f2 in s:
# ll = 2
# while f1+f2 in s:
# ll += 1
# tmp = f2
# f2 = f1+f2
# f1 = tmp
# res = max(res,ll)
# return res
# DP N^2 time N^2 space
n = len(A)
d = {}
for i in range(n):
d[A[i]] = i
dp = [[0]*n for i in range(n)]
res = 0
for i in range(n):
for j in range(i+1,n):
tar = A[i]+A[j]
if tar in d:
k = d[tar]
dp[j][k] = max(dp[j][k], dp[i][j]+1, 3)
res = max(res, max(dp[i]))
# print(res,i,j,dp)
return res
|
A sequence X_1, X_2, ..., X_n is fibonacci-like if:
n >= 3
X_i + X_{i+1} = X_{i+2} for all i + 2 <= n
Given a strictly increasing array A of positive integers forming a sequence, find the length of the longest fibonacci-like subsequence of A. If one does not exist, return 0.
(Recall that a subsequence is derived from another sequence A by deleting any number of elements (including none) from A, without changing the order of the remaining elements. For example, [3, 5, 8] is a subsequence of [3, 4, 5, 6, 7, 8].)
Example 1:
Input: [1,2,3,4,5,6,7,8]
Output: 5
Explanation:
The longest subsequence that is fibonacci-like: [1,2,3,5,8].
Example 2:
Input: [1,3,7,11,12,14,18]
Output: 3
Explanation:
The longest subsequence that is fibonacci-like:
[1,11,12], [3,11,14] or [7,11,18].
Note:
3 <= A.length <= 1000
1 <= A[0] < A[1] < ... < A[A.length - 1] <= 10^9
(The time limit has been reduced by 50% for submissions in Java, C, and C++.)
|
class Solution:
def lenLongestFibSubseq(self, A: List[int]) -> int:
s = set(A)
l = len(A)
maxL = 0
for i in range(l):
for j in range(i+1,l):
a,b = A[i], A[j]
n = 2
while a+b in s:
a,b = b,a+b
n += 1
if n > 2 and n > maxL:
maxL = n
return maxL
|
A sequence X_1, X_2, ..., X_n is fibonacci-like if:
n >= 3
X_i + X_{i+1} = X_{i+2} for all i + 2 <= n
Given a strictly increasing array A of positive integers forming a sequence, find the length of the longest fibonacci-like subsequence of A. If one does not exist, return 0.
(Recall that a subsequence is derived from another sequence A by deleting any number of elements (including none) from A, without changing the order of the remaining elements. For example, [3, 5, 8] is a subsequence of [3, 4, 5, 6, 7, 8].)
Example 1:
Input: [1,2,3,4,5,6,7,8]
Output: 5
Explanation:
The longest subsequence that is fibonacci-like: [1,2,3,5,8].
Example 2:
Input: [1,3,7,11,12,14,18]
Output: 3
Explanation:
The longest subsequence that is fibonacci-like:
[1,11,12], [3,11,14] or [7,11,18].
Note:
3 <= A.length <= 1000
1 <= A[0] < A[1] < ... < A[A.length - 1] <= 10^9
(The time limit has been reduced by 50% for submissions in Java, C, and C++.)
|
class Solution:
def lenLongestFibSubseq(self, A: List[int]) -> int:
seen = set(A)
sequence_lens = []
for i in range(len(A)):
prev_num = A[i]
for j in range(i + 1, len(A)):
curr_num = A[j]
seq_len = 2
#li = [prev_num, curr_num]
while prev_num + curr_num in seen:
#print(f'{prev_num} + {curr_num} = {prev_num + curr_num}')
seq_len += 1
next_num = prev_num + curr_num
prev_num = curr_num
curr_num = next_num
#i.append(next_num)
prev_num = A[i]
if seq_len > 2:
#print(li)
sequence_lens.append(seq_len)
return max(sequence_lens) if len(sequence_lens) > 0 else 0
|
A sequence X_1, X_2, ..., X_n is fibonacci-like if:
n >= 3
X_i + X_{i+1} = X_{i+2} for all i + 2 <= n
Given a strictly increasing array A of positive integers forming a sequence, find the length of the longest fibonacci-like subsequence of A. If one does not exist, return 0.
(Recall that a subsequence is derived from another sequence A by deleting any number of elements (including none) from A, without changing the order of the remaining elements. For example, [3, 5, 8] is a subsequence of [3, 4, 5, 6, 7, 8].)
Example 1:
Input: [1,2,3,4,5,6,7,8]
Output: 5
Explanation:
The longest subsequence that is fibonacci-like: [1,2,3,5,8].
Example 2:
Input: [1,3,7,11,12,14,18]
Output: 3
Explanation:
The longest subsequence that is fibonacci-like:
[1,11,12], [3,11,14] or [7,11,18].
Note:
3 <= A.length <= 1000
1 <= A[0] < A[1] < ... < A[A.length - 1] <= 10^9
(The time limit has been reduced by 50% for submissions in Java, C, and C++.)
|
class Solution:
def lenLongestFibSubseq(self, A: List[int]) -> int:
# a hash table
S = set(A)
maxLen = 0
n=len(A)
for i in range(0, n):
for j in range(i + 1, n):
x = A[j]
y = A[i] + A[j]
length = 2
# check until next fib
# element is found
while y in S:
# next element of fib subseq
z = x + y
x = y
y = z
length += 1
maxLen = max(maxLen, length)
return maxLen if maxLen >= 3 else 0
|
A sequence X_1, X_2, ..., X_n is fibonacci-like if:
n >= 3
X_i + X_{i+1} = X_{i+2} for all i + 2 <= n
Given a strictly increasing array A of positive integers forming a sequence, find the length of the longest fibonacci-like subsequence of A. If one does not exist, return 0.
(Recall that a subsequence is derived from another sequence A by deleting any number of elements (including none) from A, without changing the order of the remaining elements. For example, [3, 5, 8] is a subsequence of [3, 4, 5, 6, 7, 8].)
Example 1:
Input: [1,2,3,4,5,6,7,8]
Output: 5
Explanation:
The longest subsequence that is fibonacci-like: [1,2,3,5,8].
Example 2:
Input: [1,3,7,11,12,14,18]
Output: 3
Explanation:
The longest subsequence that is fibonacci-like:
[1,11,12], [3,11,14] or [7,11,18].
Note:
3 <= A.length <= 1000
1 <= A[0] < A[1] < ... < A[A.length - 1] <= 10^9
(The time limit has been reduced by 50% for submissions in Java, C, and C++.)
|
class Solution:
def lenLongestFibSubseq(self, A: List[int]) -> int:
max_length = 0
S = set(A)
for i in range(len(A)):
for j in range(i+1, len(A)):
x, y = A[i], A[j]
expected = x+y
length = 2
while expected in S:
x=y
y=expected
expected = x+y
length += 1
if length > max_length:
max_length = length
return max_length if max_length >= 3 else 0
|
A sequence X_1, X_2, ..., X_n is fibonacci-like if:
n >= 3
X_i + X_{i+1} = X_{i+2} for all i + 2 <= n
Given a strictly increasing array A of positive integers forming a sequence, find the length of the longest fibonacci-like subsequence of A. If one does not exist, return 0.
(Recall that a subsequence is derived from another sequence A by deleting any number of elements (including none) from A, without changing the order of the remaining elements. For example, [3, 5, 8] is a subsequence of [3, 4, 5, 6, 7, 8].)
Example 1:
Input: [1,2,3,4,5,6,7,8]
Output: 5
Explanation:
The longest subsequence that is fibonacci-like: [1,2,3,5,8].
Example 2:
Input: [1,3,7,11,12,14,18]
Output: 3
Explanation:
The longest subsequence that is fibonacci-like:
[1,11,12], [3,11,14] or [7,11,18].
Note:
3 <= A.length <= 1000
1 <= A[0] < A[1] < ... < A[A.length - 1] <= 10^9
(The time limit has been reduced by 50% for submissions in Java, C, and C++.)
|
class Solution:
def lenLongestFibSubseq(self, A: List[int]) -> int:
A_map = {x: i for i, x in enumerate(A)}
M = [[2] * len(A) for _ in range(len(A))]
# M[j][k] = longest fib subsequence ending with elements (A[j], A[k])
# = 1 + max(M[i][j]) over i, if A[i] + A[j] = A[k]
best = 0
for k in range(len(A)):
for j in range(k):
i = A_map.get(A[k] - A[j], None)
if i is not None and i < j:
M[j][k] = M[i][j] + 1
best = max(best, M[j][k])
# for row in M:
# print(row)
return best if best >= 3 else 0
|
A sequence X_1, X_2, ..., X_n is fibonacci-like if:
n >= 3
X_i + X_{i+1} = X_{i+2} for all i + 2 <= n
Given a strictly increasing array A of positive integers forming a sequence, find the length of the longest fibonacci-like subsequence of A. If one does not exist, return 0.
(Recall that a subsequence is derived from another sequence A by deleting any number of elements (including none) from A, without changing the order of the remaining elements. For example, [3, 5, 8] is a subsequence of [3, 4, 5, 6, 7, 8].)
Example 1:
Input: [1,2,3,4,5,6,7,8]
Output: 5
Explanation:
The longest subsequence that is fibonacci-like: [1,2,3,5,8].
Example 2:
Input: [1,3,7,11,12,14,18]
Output: 3
Explanation:
The longest subsequence that is fibonacci-like:
[1,11,12], [3,11,14] or [7,11,18].
Note:
3 <= A.length <= 1000
1 <= A[0] < A[1] < ... < A[A.length - 1] <= 10^9
(The time limit has been reduced by 50% for submissions in Java, C, and C++.)
|
class Solution:
def lenLongestFibSubseq(self, A: List[int]) -> int:
A_map = {x: i for i, x in enumerate(A)}
M = [[2] * len(A) for _ in range(len(A))]
# M[j][k] = longest fib subsequence ending with elements (A[j], A[k])
# = 1 + max(M[i][j]) over i, if A[i] + A[j] = A[k]
best = 0
for k in range(len(A)):
for j in range(1, k):
i = A_map.get(A[k] - A[j], None)
if i is not None and i < j:
M[j][k] = M[i][j] + 1
best = max(best, M[j][k])
# for row in M:
# print(row)
return best if best >= 3 else 0
|
A sequence X_1, X_2, ..., X_n is fibonacci-like if:
n >= 3
X_i + X_{i+1} = X_{i+2} for all i + 2 <= n
Given a strictly increasing array A of positive integers forming a sequence, find the length of the longest fibonacci-like subsequence of A. If one does not exist, return 0.
(Recall that a subsequence is derived from another sequence A by deleting any number of elements (including none) from A, without changing the order of the remaining elements. For example, [3, 5, 8] is a subsequence of [3, 4, 5, 6, 7, 8].)
Example 1:
Input: [1,2,3,4,5,6,7,8]
Output: 5
Explanation:
The longest subsequence that is fibonacci-like: [1,2,3,5,8].
Example 2:
Input: [1,3,7,11,12,14,18]
Output: 3
Explanation:
The longest subsequence that is fibonacci-like:
[1,11,12], [3,11,14] or [7,11,18].
Note:
3 <= A.length <= 1000
1 <= A[0] < A[1] < ... < A[A.length - 1] <= 10^9
(The time limit has been reduced by 50% for submissions in Java, C, and C++.)
|
class Solution:
def lenLongestFibSubseq(self, A: List[int]) -> int:
index = {x: i for i, x in enumerate(A)}
longest = 0
board = []
for i in range(len(A)):
row = []
row = [2] * len(A)
board.append(row)
for j in range(len(A)):
for k in range(j + 1, len(A)):
a = A[k] - A[j]
if a < A[j]:
i = index.get(a, None)
if i != None:
board[j][k] = board[i][j] + 1
longest = max(longest, board[j][k])
return longest
|
A sequence X_1, X_2, ..., X_n is fibonacci-like if:
n >= 3
X_i + X_{i+1} = X_{i+2} for all i + 2 <= n
Given a strictly increasing array A of positive integers forming a sequence, find the length of the longest fibonacci-like subsequence of A. If one does not exist, return 0.
(Recall that a subsequence is derived from another sequence A by deleting any number of elements (including none) from A, without changing the order of the remaining elements. For example, [3, 5, 8] is a subsequence of [3, 4, 5, 6, 7, 8].)
Example 1:
Input: [1,2,3,4,5,6,7,8]
Output: 5
Explanation:
The longest subsequence that is fibonacci-like: [1,2,3,5,8].
Example 2:
Input: [1,3,7,11,12,14,18]
Output: 3
Explanation:
The longest subsequence that is fibonacci-like:
[1,11,12], [3,11,14] or [7,11,18].
Note:
3 <= A.length <= 1000
1 <= A[0] < A[1] < ... < A[A.length - 1] <= 10^9
(The time limit has been reduced by 50% for submissions in Java, C, and C++.)
|
class Solution:
def lenLongestFibSubseq(self, A: List[int]) -> int:
A_map = {x: i for i, x in enumerate(A)}
M = [[2] * len(A) for _ in range(len(A))]
# M[j][k] = longest fib subsequence ending with elements (A[j], A[k])
# = 1 + max(M[i][j]) over i, if A[i] + A[j] = A[k]
best = 0
for k in range(2, len(A)):
for j in range(1, k):
i = A_map.get(A[k] - A[j], None)
if i is not None and i < j:
M[j][k] = M[i][j] + 1
best = max(best, M[j][k])
# for row in M:
# print(row)
return best if best >= 3 else 0
|
A sequence X_1, X_2, ..., X_n is fibonacci-like if:
n >= 3
X_i + X_{i+1} = X_{i+2} for all i + 2 <= n
Given a strictly increasing array A of positive integers forming a sequence, find the length of the longest fibonacci-like subsequence of A. If one does not exist, return 0.
(Recall that a subsequence is derived from another sequence A by deleting any number of elements (including none) from A, without changing the order of the remaining elements. For example, [3, 5, 8] is a subsequence of [3, 4, 5, 6, 7, 8].)
Example 1:
Input: [1,2,3,4,5,6,7,8]
Output: 5
Explanation:
The longest subsequence that is fibonacci-like: [1,2,3,5,8].
Example 2:
Input: [1,3,7,11,12,14,18]
Output: 3
Explanation:
The longest subsequence that is fibonacci-like:
[1,11,12], [3,11,14] or [7,11,18].
Note:
3 <= A.length <= 1000
1 <= A[0] < A[1] < ... < A[A.length - 1] <= 10^9
(The time limit has been reduced by 50% for submissions in Java, C, and C++.)
|
class Solution:
def lenLongestFibSubseq(self, A: List[int]) -> int:
index = {A[i]: i for i in range(len(A))}
longest = {}
ans = 0
length = len(A)
for i in range(length):
for j in range(i):
x = A[i] - A[j]
m = index.get(x)
if m is not None and m < j:
longest[(j, i)] = longest.get((m, j)) + 1 if longest.get((m, j)) is not None else 3
ans = max(ans, longest[(j, i)])
else:
continue
return ans if ans >= 3 else 0
|
A sequence X_1, X_2, ..., X_n is fibonacci-like if:
n >= 3
X_i + X_{i+1} = X_{i+2} for all i + 2 <= n
Given a strictly increasing array A of positive integers forming a sequence, find the length of the longest fibonacci-like subsequence of A. If one does not exist, return 0.
(Recall that a subsequence is derived from another sequence A by deleting any number of elements (including none) from A, without changing the order of the remaining elements. For example, [3, 5, 8] is a subsequence of [3, 4, 5, 6, 7, 8].)
Example 1:
Input: [1,2,3,4,5,6,7,8]
Output: 5
Explanation:
The longest subsequence that is fibonacci-like: [1,2,3,5,8].
Example 2:
Input: [1,3,7,11,12,14,18]
Output: 3
Explanation:
The longest subsequence that is fibonacci-like:
[1,11,12], [3,11,14] or [7,11,18].
Note:
3 <= A.length <= 1000
1 <= A[0] < A[1] < ... < A[A.length - 1] <= 10^9
(The time limit has been reduced by 50% for submissions in Java, C, and C++.)
|
class Solution:
def lenLongestFibSubseq(self, A: List[int]) -> int:
ret = 0
n = len(A)
mapping = {v:i for i, v in enumerate(A)}
for i in range(n):
for j in range(i+1, n):
prev_, next_ = A[j], A[i]+A[j]
length = 2
while next_ in mapping:
length += 1
prev_, next_ = next_, prev_+next_
if length > 2:
ret = max(ret, length)
return ret
|
A sequence X_1, X_2, ..., X_n is fibonacci-like if:
n >= 3
X_i + X_{i+1} = X_{i+2} for all i + 2 <= n
Given a strictly increasing array A of positive integers forming a sequence, find the length of the longest fibonacci-like subsequence of A. If one does not exist, return 0.
(Recall that a subsequence is derived from another sequence A by deleting any number of elements (including none) from A, without changing the order of the remaining elements. For example, [3, 5, 8] is a subsequence of [3, 4, 5, 6, 7, 8].)
Example 1:
Input: [1,2,3,4,5,6,7,8]
Output: 5
Explanation:
The longest subsequence that is fibonacci-like: [1,2,3,5,8].
Example 2:
Input: [1,3,7,11,12,14,18]
Output: 3
Explanation:
The longest subsequence that is fibonacci-like:
[1,11,12], [3,11,14] or [7,11,18].
Note:
3 <= A.length <= 1000
1 <= A[0] < A[1] < ... < A[A.length - 1] <= 10^9
(The time limit has been reduced by 50% for submissions in Java, C, and C++.)
|
class Solution:
def lenLongestFibSubseq(self, A: List[int]) -> int:
val2idx = {val: i for i, val in enumerate(A)}
longest = collections.defaultdict(lambda: 2) #defaultval为2
longest[(0,0)] = 1
res = 0
for k in range(2, len(A)):
for j in range(k):
i = val2idx.get(A[k] - A[j], None)
if i != None and i < j: # i < j to control increasing order
longest[(j,k)] = longest[(i,j)] + 1
res = max(res, longest[(j,k)])
return res if res >= 3 else 0
# 不能只用一个数字做为ending。比如[1,2,3,4].如果只用一个数字,那么end为3时候longest是3,但是end为4的时候实际上是[1,3,4],而不是[1,2,3,4],不能直接end3 + 1
|
A sequence X_1, X_2, ..., X_n is fibonacci-like if:
n >= 3
X_i + X_{i+1} = X_{i+2} for all i + 2 <= n
Given a strictly increasing array A of positive integers forming a sequence, find the length of the longest fibonacci-like subsequence of A. If one does not exist, return 0.
(Recall that a subsequence is derived from another sequence A by deleting any number of elements (including none) from A, without changing the order of the remaining elements. For example, [3, 5, 8] is a subsequence of [3, 4, 5, 6, 7, 8].)
Example 1:
Input: [1,2,3,4,5,6,7,8]
Output: 5
Explanation:
The longest subsequence that is fibonacci-like: [1,2,3,5,8].
Example 2:
Input: [1,3,7,11,12,14,18]
Output: 3
Explanation:
The longest subsequence that is fibonacci-like:
[1,11,12], [3,11,14] or [7,11,18].
Note:
3 <= A.length <= 1000
1 <= A[0] < A[1] < ... < A[A.length - 1] <= 10^9
(The time limit has been reduced by 50% for submissions in Java, C, and C++.)
|
class Solution:
def lenLongestFibSubseq(self, A: List[int]) -> int:
dp = [ [2]*len(A) for i in range(len(A))]
d= {}
for i in range(len(A)):
d[A[i]] = i
ans = 2
for i in range(1,len(A)):
for j in range(i):
fn = A[i]+A[j]
if fn in list(d.keys()) and d[fn] > i:
length = dp[j][i]
dp[i][d[fn]] = max(dp[i][d[fn]],1+length)
ans = max(ans,dp[i][d[fn]])
if ans == 2:
return 0
return ans
|
A sequence X_1, X_2, ..., X_n is fibonacci-like if:
n >= 3
X_i + X_{i+1} = X_{i+2} for all i + 2 <= n
Given a strictly increasing array A of positive integers forming a sequence, find the length of the longest fibonacci-like subsequence of A. If one does not exist, return 0.
(Recall that a subsequence is derived from another sequence A by deleting any number of elements (including none) from A, without changing the order of the remaining elements. For example, [3, 5, 8] is a subsequence of [3, 4, 5, 6, 7, 8].)
Example 1:
Input: [1,2,3,4,5,6,7,8]
Output: 5
Explanation:
The longest subsequence that is fibonacci-like: [1,2,3,5,8].
Example 2:
Input: [1,3,7,11,12,14,18]
Output: 3
Explanation:
The longest subsequence that is fibonacci-like:
[1,11,12], [3,11,14] or [7,11,18].
Note:
3 <= A.length <= 1000
1 <= A[0] < A[1] < ... < A[A.length - 1] <= 10^9
(The time limit has been reduced by 50% for submissions in Java, C, and C++.)
|
class Solution:
def lenLongestFibSubseq(self, A: List[int]) -> int:
n = len(A)
s = set(A)
if n <= 2:
return 0
ans = 0
for i in range(n - 2):
for j in range(i + 1, n - 1):
a, b = A[j], A[i] + A[j]
count = 2
while b in s:
count += 1
a, b = b, a + b
if count > 2:
ans = max(ans, count)
return ans
|
A sequence X_1, X_2, ..., X_n is fibonacci-like if:
n >= 3
X_i + X_{i+1} = X_{i+2} for all i + 2 <= n
Given a strictly increasing array A of positive integers forming a sequence, find the length of the longest fibonacci-like subsequence of A. If one does not exist, return 0.
(Recall that a subsequence is derived from another sequence A by deleting any number of elements (including none) from A, without changing the order of the remaining elements. For example, [3, 5, 8] is a subsequence of [3, 4, 5, 6, 7, 8].)
Example 1:
Input: [1,2,3,4,5,6,7,8]
Output: 5
Explanation:
The longest subsequence that is fibonacci-like: [1,2,3,5,8].
Example 2:
Input: [1,3,7,11,12,14,18]
Output: 3
Explanation:
The longest subsequence that is fibonacci-like:
[1,11,12], [3,11,14] or [7,11,18].
Note:
3 <= A.length <= 1000
1 <= A[0] < A[1] < ... < A[A.length - 1] <= 10^9
(The time limit has been reduced by 50% for submissions in Java, C, and C++.)
|
from collections import defaultdict
class Solution:
def lenLongestFibSubseq(self, A: List[int]) -> int:
A_indices = {a: i for i, a in enumerate(A)}
lengths = defaultdict(lambda: 2)
best = 0
for k in range(len(A) - 1, 1, -1):
i = 0
j = k - 1
while i < j:
if A[i] + A[j] < A[k]:
i += 1
elif A[i] + A[j] > A[k]:
j -= 1
else:
lengths[i, j] = lengths[j, k] + 1
best = max(best, lengths[i, j])
i += 1
j -= 1
return best
|
Given an array of citations sorted in ascending order (each citation is a non-negative integer) of a researcher, write a function to compute the researcher's h-index.
According to the definition of h-index on Wikipedia: "A scientist has index h if h of his/her N papers have at least h citations each, and the other N − h papers have no more than h citations each."
Example:
Input: citations = [0,1,3,5,6]
Output: 3
Explanation: [0,1,3,5,6] means the researcher has 5 papers in total and each of them had
received 0, 1, 3, 5, 6 citations respectively.
Since the researcher has 3 papers with at least 3 citations each and the remaining
two with no more than 3 citations each, her h-index is 3.
Note:
If there are several possible values for h, the maximum one is taken as the h-index.
Follow up:
This is a follow up problem to H-Index, where citations is now guaranteed to be sorted in ascending order.
Could you solve it in logarithmic time complexity?
|
class Solution(object):
def hIndex(self, citations):
"""
:type citations: List[int]
:rtype: int
"""
n = len(citations)
l = 0
r = n-1
while l <= r:
m = (l + r) // 2
if m == 0 and citations[m] >= n - m or citations[m-1] < n - (m-1) and citations[m] >= n-m:
return n-m
if citations[m] < n - m:
l = m+1
else:
r = m
return 0
|
Given an array of citations sorted in ascending order (each citation is a non-negative integer) of a researcher, write a function to compute the researcher's h-index.
According to the definition of h-index on Wikipedia: "A scientist has index h if h of his/her N papers have at least h citations each, and the other N − h papers have no more than h citations each."
Example:
Input: citations = [0,1,3,5,6]
Output: 3
Explanation: [0,1,3,5,6] means the researcher has 5 papers in total and each of them had
received 0, 1, 3, 5, 6 citations respectively.
Since the researcher has 3 papers with at least 3 citations each and the remaining
two with no more than 3 citations each, her h-index is 3.
Note:
If there are several possible values for h, the maximum one is taken as the h-index.
Follow up:
This is a follow up problem to H-Index, where citations is now guaranteed to be sorted in ascending order.
Could you solve it in logarithmic time complexity?
|
class Solution:
def hIndex(self, citations):
"""
:type citations: List[int]
:rtype: int
"""
n = len(citations)
l, r = 0, n - 1
while l <= r:
m = (l + r) // 2
if citations[m] >= n - m:
r = m - 1
else:
l = m + 1
return n - r - 1
|
Given an array of citations sorted in ascending order (each citation is a non-negative integer) of a researcher, write a function to compute the researcher's h-index.
According to the definition of h-index on Wikipedia: "A scientist has index h if h of his/her N papers have at least h citations each, and the other N − h papers have no more than h citations each."
Example:
Input: citations = [0,1,3,5,6]
Output: 3
Explanation: [0,1,3,5,6] means the researcher has 5 papers in total and each of them had
received 0, 1, 3, 5, 6 citations respectively.
Since the researcher has 3 papers with at least 3 citations each and the remaining
two with no more than 3 citations each, her h-index is 3.
Note:
If there are several possible values for h, the maximum one is taken as the h-index.
Follow up:
This is a follow up problem to H-Index, where citations is now guaranteed to be sorted in ascending order.
Could you solve it in logarithmic time complexity?
|
class Solution:
def hIndex(self, citations):
"""
:type citations: List[int]
:rtype: int
"""
c = citations
if not c:
return 0
s, e = 0, len(c) - 1
if c[s] >= len(c):
return len(c)
if c[e] < 1:
return 0
while s < e - 1:
m = s + int((e - s) / 2)
if c[m] >= len(c) - m:
e = m
else:
s = m
return len(c) - e
|
Given an array of citations sorted in ascending order (each citation is a non-negative integer) of a researcher, write a function to compute the researcher's h-index.
According to the definition of h-index on Wikipedia: "A scientist has index h if h of his/her N papers have at least h citations each, and the other N − h papers have no more than h citations each."
Example:
Input: citations = [0,1,3,5,6]
Output: 3
Explanation: [0,1,3,5,6] means the researcher has 5 papers in total and each of them had
received 0, 1, 3, 5, 6 citations respectively.
Since the researcher has 3 papers with at least 3 citations each and the remaining
two with no more than 3 citations each, her h-index is 3.
Note:
If there are several possible values for h, the maximum one is taken as the h-index.
Follow up:
This is a follow up problem to H-Index, where citations is now guaranteed to be sorted in ascending order.
Could you solve it in logarithmic time complexity?
|
class Solution:
"""
time: O(logn)
"""
def hIndex(self, citations):
"""
:type citations: List[int]
:rtype: int
"""
if not citations:
return 0
n = len(citations)
left, right = 0, n - 1
while left + 1 < right:
mid = (left + right) // 2
if citations[mid] >= n - mid:
right = mid
else:
left = mid
for mid in (left, right):
if citations[mid] >= n - mid:
return n - mid
return 0
|
Given an array of citations sorted in ascending order (each citation is a non-negative integer) of a researcher, write a function to compute the researcher's h-index.
According to the definition of h-index on Wikipedia: "A scientist has index h if h of his/her N papers have at least h citations each, and the other N − h papers have no more than h citations each."
Example:
Input: citations = [0,1,3,5,6]
Output: 3
Explanation: [0,1,3,5,6] means the researcher has 5 papers in total and each of them had
received 0, 1, 3, 5, 6 citations respectively.
Since the researcher has 3 papers with at least 3 citations each and the remaining
two with no more than 3 citations each, her h-index is 3.
Note:
If there are several possible values for h, the maximum one is taken as the h-index.
Follow up:
This is a follow up problem to H-Index, where citations is now guaranteed to be sorted in ascending order.
Could you solve it in logarithmic time complexity?
|
class Solution:
def hIndex(self, citations):
"""
:type citations: List[int]
:rtype: int
"""
h = 0
count = 0
for c in citations[::-1]:
if c <= count:
return count
count += 1
return count
|
Given an array of citations sorted in ascending order (each citation is a non-negative integer) of a researcher, write a function to compute the researcher's h-index.
According to the definition of h-index on Wikipedia: "A scientist has index h if h of his/her N papers have at least h citations each, and the other N − h papers have no more than h citations each."
Example:
Input: citations = [0,1,3,5,6]
Output: 3
Explanation: [0,1,3,5,6] means the researcher has 5 papers in total and each of them had
received 0, 1, 3, 5, 6 citations respectively.
Since the researcher has 3 papers with at least 3 citations each and the remaining
two with no more than 3 citations each, her h-index is 3.
Note:
If there are several possible values for h, the maximum one is taken as the h-index.
Follow up:
This is a follow up problem to H-Index, where citations is now guaranteed to be sorted in ascending order.
Could you solve it in logarithmic time complexity?
|
class Solution:
def hIndex(self, citations):
"""
:type citations: List[int]
:rtype: int
"""
l, r, res = 0, len(citations) - 1, 0
while l <= r:
mid = (l + r) // 2
if len(citations) - mid <= citations[mid]: res, r = len(citations) - mid, r - 1
else: l = mid + 1
return res
|
Given an array of citations sorted in ascending order (each citation is a non-negative integer) of a researcher, write a function to compute the researcher's h-index.
According to the definition of h-index on Wikipedia: "A scientist has index h if h of his/her N papers have at least h citations each, and the other N − h papers have no more than h citations each."
Example:
Input: citations = [0,1,3,5,6]
Output: 3
Explanation: [0,1,3,5,6] means the researcher has 5 papers in total and each of them had
received 0, 1, 3, 5, 6 citations respectively.
Since the researcher has 3 papers with at least 3 citations each and the remaining
two with no more than 3 citations each, her h-index is 3.
Note:
If there are several possible values for h, the maximum one is taken as the h-index.
Follow up:
This is a follow up problem to H-Index, where citations is now guaranteed to be sorted in ascending order.
Could you solve it in logarithmic time complexity?
|
class Solution:
def hIndex(self, citations):
"""
:type citations: List[int]
:rtype: int
"""
citations.sort(reverse=True)
for idx in range(len(citations)):
if idx + 1> citations[idx]:
return idx
return len(citations)
|
Given an array of citations sorted in ascending order (each citation is a non-negative integer) of a researcher, write a function to compute the researcher's h-index.
According to the definition of h-index on Wikipedia: "A scientist has index h if h of his/her N papers have at least h citations each, and the other N − h papers have no more than h citations each."
Example:
Input: citations = [0,1,3,5,6]
Output: 3
Explanation: [0,1,3,5,6] means the researcher has 5 papers in total and each of them had
received 0, 1, 3, 5, 6 citations respectively.
Since the researcher has 3 papers with at least 3 citations each and the remaining
two with no more than 3 citations each, her h-index is 3.
Note:
If there are several possible values for h, the maximum one is taken as the h-index.
Follow up:
This is a follow up problem to H-Index, where citations is now guaranteed to be sorted in ascending order.
Could you solve it in logarithmic time complexity?
|
class Solution:
def hIndex(self, citations):
"""
:type citations: List[int]
:rtype: int
"""
citations.sort()
for i in range(len(citations)-1, -1, -1):
if citations[i] >= len(citations)-i and (i == 0 or citations[i-1] <= len(citations)-i):
return len(citations)-i
return 0
|
Given an array of citations sorted in ascending order (each citation is a non-negative integer) of a researcher, write a function to compute the researcher's h-index.
According to the definition of h-index on Wikipedia: "A scientist has index h if h of his/her N papers have at least h citations each, and the other N − h papers have no more than h citations each."
Example:
Input: citations = [0,1,3,5,6]
Output: 3
Explanation: [0,1,3,5,6] means the researcher has 5 papers in total and each of them had
received 0, 1, 3, 5, 6 citations respectively.
Since the researcher has 3 papers with at least 3 citations each and the remaining
two with no more than 3 citations each, her h-index is 3.
Note:
If there are several possible values for h, the maximum one is taken as the h-index.
Follow up:
This is a follow up problem to H-Index, where citations is now guaranteed to be sorted in ascending order.
Could you solve it in logarithmic time complexity?
|
class Solution:
def hIndex(self, citations):
"""
:type citations: List[int]
:rtype: int
"""
# my solution......beat 95 %
l = len(citations)
if l == 0: return 0
if l == 1:
if citations[0] == 0: return 0
else: return 1
if min(citations) >= l: return l
citations = citations[::-1]
count = 0
thres = 0
i = 0
while i < len(citations):
if thres >= count:
thres = citations[i]
count += 1
i += 1
else:
return count-1
return count-1
|
Given an array of citations sorted in ascending order (each citation is a non-negative integer) of a researcher, write a function to compute the researcher's h-index.
According to the definition of h-index on Wikipedia: "A scientist has index h if h of his/her N papers have at least h citations each, and the other N − h papers have no more than h citations each."
Example:
Input: citations = [0,1,3,5,6]
Output: 3
Explanation: [0,1,3,5,6] means the researcher has 5 papers in total and each of them had
received 0, 1, 3, 5, 6 citations respectively.
Since the researcher has 3 papers with at least 3 citations each and the remaining
two with no more than 3 citations each, her h-index is 3.
Note:
If there are several possible values for h, the maximum one is taken as the h-index.
Follow up:
This is a follow up problem to H-Index, where citations is now guaranteed to be sorted in ascending order.
Could you solve it in logarithmic time complexity?
|
class Solution:
def hIndex(self, citations):
"""
:type citations: List[int]
:rtype: int
"""
# my solution......beat 100 %
l = len(citations)
if l == 0: return 0 # shit testcase: []
if l == 1:
if citations[0] == 0: return 0 # shit testcase: [0]
else: return 1 # for testcase: [1], [2] or [100] etc...
if min(citations) >= l: return l # for testcase: [2,3], [5,8], [3,4,5], [7,8,9,9] etc...
citations = citations[::-1]
count = 0
thres = 0 # (count, thres): this author has "count" articles with citations >= thres
i = 0
while i < len(citations):
if thres >= count:
thres = citations[i]
count += 1
i += 1
else:
return count - 1
return count - 1
|
Given a string S and a string T, count the number of distinct subsequences of S which equals T.
A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, "ACE" is a subsequence of "ABCDE" while "AEC" is not).
Example 1:
Input: S = "rabbbit", T = "rabbit"
Output: 3
Explanation:
As shown below, there are 3 ways you can generate "rabbit" from S.
(The caret symbol ^ means the chosen letters)
rabbbit
^^^^ ^^
rabbbit
^^ ^^^^
rabbbit
^^^ ^^^
Example 2:
Input: S = "babgbag", T = "bag"
Output: 5
Explanation:
As shown below, there are 5 ways you can generate "bag" from S.
(The caret symbol ^ means the chosen letters)
babgbag
^^ ^
babgbag
^^ ^
babgbag
^ ^^
babgbag
^ ^^
babgbag
^^^
|
class Solution:
def numDistinct(self, s, t):
"""
:type s: str
:type t: str
:rtype: int
"""
setOft=set(t)
news=""
for ch in s:
if ch in setOft:
news+=ch
dp=[[1 for i in range(len(news)+1)] for j in range(len(t)+1)]
for j in range(1,len(t)+1):
dp[j][0]=0
for i in range(len(t)):
for j in range(len(news)):
if t[i]==news[j]:
dp[i+1][j+1]=dp[i][j]+dp[i+1][j]
else:
dp[i+1][j+1]=dp[i+1][j]
return dp[len(t)][len(news)]
|
Given a string S and a string T, count the number of distinct subsequences of S which equals T.
A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, "ACE" is a subsequence of "ABCDE" while "AEC" is not).
Example 1:
Input: S = "rabbbit", T = "rabbit"
Output: 3
Explanation:
As shown below, there are 3 ways you can generate "rabbit" from S.
(The caret symbol ^ means the chosen letters)
rabbbit
^^^^ ^^
rabbbit
^^ ^^^^
rabbbit
^^^ ^^^
Example 2:
Input: S = "babgbag", T = "bag"
Output: 5
Explanation:
As shown below, there are 5 ways you can generate "bag" from S.
(The caret symbol ^ means the chosen letters)
babgbag
^^ ^
babgbag
^^ ^
babgbag
^ ^^
babgbag
^ ^^
babgbag
^^^
|
class Solution:
def __init__(self):
self.dp = {}
self.s = ""
self.t = ""
self.letter2Indices = {}
def numDistinct(self, s, t):
"""
:type s: str
:type t: str
:rtype: int
"""
if len(s) < len(t):
return 0
if not t:
return 1
self.s = s.lower()
self.t = t.lower()
length = len(s)
for i in range(len(t)):
self.dp[i] = [-1] * length
for i in range(length):
letter = self.s[i]
if letter in self.letter2Indices:
self.letter2Indices[letter].append(i)
else:
self.letter2Indices[letter] = list([i])
return self.numSubseq(0, 0)
def numSubseq(self, startS, startT):
if startT >= len(self.t):
return 1
if startS >= len(self.s):
return 0
if self.dp[startT][startS] >= 0:
return self.dp[startT][startS]
letter = self.t[startT]
count = 0
firstMatch = -1
if letter in self.letter2Indices:
for i in self.letter2Indices[letter]:
if i >= startS:
count += self.numSubseq(i+1, startT+1)
if firstMatch < 0:
# We can directly fill dp[startT][startS:firstMatch-1] with the same number
firstMatch = i
self.dp[startT][startS] = count
for i in range(startS + 1, firstMatch):
self.dp[startT][i] = count
return count
|
Given a string S and a string T, count the number of distinct subsequences of S which equals T.
A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, "ACE" is a subsequence of "ABCDE" while "AEC" is not).
Example 1:
Input: S = "rabbbit", T = "rabbit"
Output: 3
Explanation:
As shown below, there are 3 ways you can generate "rabbit" from S.
(The caret symbol ^ means the chosen letters)
rabbbit
^^^^ ^^
rabbbit
^^ ^^^^
rabbbit
^^^ ^^^
Example 2:
Input: S = "babgbag", T = "bag"
Output: 5
Explanation:
As shown below, there are 5 ways you can generate "bag" from S.
(The caret symbol ^ means the chosen letters)
babgbag
^^ ^
babgbag
^^ ^
babgbag
^ ^^
babgbag
^ ^^
babgbag
^^^
|
class Solution:
def numDistinct(self, s, t):
"""
:type s: str
:type t: str
:rtype: int
"""
result = (len(t) + 1) * [0]
result[0] = 1
for j in range(len(s)):
for i in reversed(range(len(t))):
if s[j] == t[i]:
result[i + 1] += result[i]
return result[-1]
|
Given a string S and a string T, count the number of distinct subsequences of S which equals T.
A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, "ACE" is a subsequence of "ABCDE" while "AEC" is not).
Example 1:
Input: S = "rabbbit", T = "rabbit"
Output: 3
Explanation:
As shown below, there are 3 ways you can generate "rabbit" from S.
(The caret symbol ^ means the chosen letters)
rabbbit
^^^^ ^^
rabbbit
^^ ^^^^
rabbbit
^^^ ^^^
Example 2:
Input: S = "babgbag", T = "bag"
Output: 5
Explanation:
As shown below, there are 5 ways you can generate "bag" from S.
(The caret symbol ^ means the chosen letters)
babgbag
^^ ^
babgbag
^^ ^
babgbag
^ ^^
babgbag
^ ^^
babgbag
^^^
|
class Solution:
def numDistinct(self, s, t):
"""
:type s: str
:type t: str
:rtype: int
"""
row = len(s) + 1
col = len(t) + 1
dp = [0]*col
dp[0] = 1
for i in range(1, row):
pre = dp[:]
# print(pre)
for j in range(1, col):
if s[i-1] == t[j-1]:
dp[j] += pre[j-1]
# print(dp)
return dp[-1]
|
Given a string S and a string T, count the number of distinct subsequences of S which equals T.
A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, "ACE" is a subsequence of "ABCDE" while "AEC" is not).
Example 1:
Input: S = "rabbbit", T = "rabbit"
Output: 3
Explanation:
As shown below, there are 3 ways you can generate "rabbit" from S.
(The caret symbol ^ means the chosen letters)
rabbbit
^^^^ ^^
rabbbit
^^ ^^^^
rabbbit
^^^ ^^^
Example 2:
Input: S = "babgbag", T = "bag"
Output: 5
Explanation:
As shown below, there are 5 ways you can generate "bag" from S.
(The caret symbol ^ means the chosen letters)
babgbag
^^ ^
babgbag
^^ ^
babgbag
^ ^^
babgbag
^ ^^
babgbag
^^^
|
class Solution:
def numDistinct(self, s, t):
"""
:type s: str
:type t: str
:rtype: int
"""
if len(s) < len(t):
return 0
dp = [0] * len(s)
for i in range(len(s)):
dp[i] = dp[i-1] if i > 0 else 0
if s[i] == t[0]:
dp[i] += 1
for i, ti in enumerate(t[1:]):
dp2 = [0] * len(s)
for j in range(i+1, len(s)):
dp2[j] = dp2[j-1]
if s[j] == ti:
dp2[j] += dp[j-1]
dp = dp2
return dp[-1]
|
There are N dominoes in a line, and we place each domino vertically upright.
In the beginning, we simultaneously push some of the dominoes either to the left or to the right.
After each second, each domino that is falling to the left pushes the adjacent domino on the left.
Similarly, the dominoes falling to the right push their adjacent dominoes standing on the right.
When a vertical domino has dominoes falling on it from both sides, it stays still due to the balance of the forces.
For the purposes of this question, we will consider that a falling domino expends no additional force to a falling or already fallen domino.
Given a string "S" representing the initial state. S[i] = 'L', if the i-th domino has been pushed to the left; S[i] = 'R', if the i-th domino has been pushed to the right; S[i] = '.', if the i-th domino has not been pushed.
Return a string representing the final state.
Example 1:
Input: ".L.R...LR..L.."
Output: "LL.RR.LLRRLL.."
Example 2:
Input: "RR.L"
Output: "RR.L"
Explanation: The first domino expends no additional force on the second domino.
Note:
0 <= N <= 10^5
String dominoes contains only 'L', 'R' and '.'
|
INF = float('inf')
class Solution:
def pushDominoes(self, dominoes: str) -> str:
n = len(dominoes)
d1 = [-1] * n
d2 = [-1] * n
cnt = INF
for i in range(n - 1, -1, -1):
if dominoes[i] == 'L':
cnt = 0
elif dominoes[i] == '.':
cnt += 1
elif dominoes[i] == 'R':
cnt = INF
d1[i] = cnt
cnt = INF
for i in range(n):
if dominoes[i] == 'R':
cnt = 0
elif dominoes[i] == '.':
cnt += 1
elif dominoes[i] == 'L':
cnt = INF
d2[i] = cnt
ret = []
for i in range(n):
if d1[i] == d2[i]:
ret.append('.')
elif d1[i] < d2[i]:
ret.append('L')
else:
ret.append('R')
return ''.join(ret)
|
There are N dominoes in a line, and we place each domino vertically upright.
In the beginning, we simultaneously push some of the dominoes either to the left or to the right.
After each second, each domino that is falling to the left pushes the adjacent domino on the left.
Similarly, the dominoes falling to the right push their adjacent dominoes standing on the right.
When a vertical domino has dominoes falling on it from both sides, it stays still due to the balance of the forces.
For the purposes of this question, we will consider that a falling domino expends no additional force to a falling or already fallen domino.
Given a string "S" representing the initial state. S[i] = 'L', if the i-th domino has been pushed to the left; S[i] = 'R', if the i-th domino has been pushed to the right; S[i] = '.', if the i-th domino has not been pushed.
Return a string representing the final state.
Example 1:
Input: ".L.R...LR..L.."
Output: "LL.RR.LLRRLL.."
Example 2:
Input: "RR.L"
Output: "RR.L"
Explanation: The first domino expends no additional force on the second domino.
Note:
0 <= N <= 10^5
String dominoes contains only 'L', 'R' and '.'
|
class Solution:
def pushDominoes(self, dominoes: str) -> str:
n = len(dominoes)
d = [0] * n
force = 0
for i in range(n):
c = dominoes[i]
if c == 'R':
force = n
elif c == 'L':
force = 0
else:
force = max(force - 1, 0)
d[i] += force
force = 0
for i in range(n-1, -1, -1):
c = dominoes[i]
if c == 'R':
force = 0
elif c == 'L':
force = n
else:
force = max(force - 1, 0)
d[i] -= force
def inner():
for f in d:
if f == 0:
yield '.'
elif f > 0:
yield 'R'
else:
yield 'L'
return ''.join(inner())
|
There are N dominoes in a line, and we place each domino vertically upright.
In the beginning, we simultaneously push some of the dominoes either to the left or to the right.
After each second, each domino that is falling to the left pushes the adjacent domino on the left.
Similarly, the dominoes falling to the right push their adjacent dominoes standing on the right.
When a vertical domino has dominoes falling on it from both sides, it stays still due to the balance of the forces.
For the purposes of this question, we will consider that a falling domino expends no additional force to a falling or already fallen domino.
Given a string "S" representing the initial state. S[i] = 'L', if the i-th domino has been pushed to the left; S[i] = 'R', if the i-th domino has been pushed to the right; S[i] = '.', if the i-th domino has not been pushed.
Return a string representing the final state.
Example 1:
Input: ".L.R...LR..L.."
Output: "LL.RR.LLRRLL.."
Example 2:
Input: "RR.L"
Output: "RR.L"
Explanation: The first domino expends no additional force on the second domino.
Note:
0 <= N <= 10^5
String dominoes contains only 'L', 'R' and '.'
|
class Solution:
def pushDominoes(self, dominoes: str) -> str:
n = len(dominoes)
force = [0] * n
f = 0
for i in range(n):
if dominoes[i] == 'R':
f = n
elif dominoes[i] == 'L':
f = 0
else:
f = max(f-1, 0)
force[i] += f
for i in range(n-1, -1, -1):
if dominoes[i] == 'L':
f = n
elif dominoes[i] == 'R':
f = 0
else:
f = max(f-1, 0)
force[i] -= f
return ''.join('.' if f==0 else 'R' if f > 0 else 'L' for f in force)
|
There are N dominoes in a line, and we place each domino vertically upright.
In the beginning, we simultaneously push some of the dominoes either to the left or to the right.
After each second, each domino that is falling to the left pushes the adjacent domino on the left.
Similarly, the dominoes falling to the right push their adjacent dominoes standing on the right.
When a vertical domino has dominoes falling on it from both sides, it stays still due to the balance of the forces.
For the purposes of this question, we will consider that a falling domino expends no additional force to a falling or already fallen domino.
Given a string "S" representing the initial state. S[i] = 'L', if the i-th domino has been pushed to the left; S[i] = 'R', if the i-th domino has been pushed to the right; S[i] = '.', if the i-th domino has not been pushed.
Return a string representing the final state.
Example 1:
Input: ".L.R...LR..L.."
Output: "LL.RR.LLRRLL.."
Example 2:
Input: "RR.L"
Output: "RR.L"
Explanation: The first domino expends no additional force on the second domino.
Note:
0 <= N <= 10^5
String dominoes contains only 'L', 'R' and '.'
|
class Solution:
def pushDominoes(self, dominoes: str) -> str:
l = len(dominoes)
right_force = [0]*l
left_force = [0]*l
force1 = 0
force2 = 0
for i in range(l):
if dominoes[i]=='R':
force1 = l
elif dominoes[i]=='L':
force1 = 0
else:
force1 = max(force1 - 1, 0)
right_force[i] += force1
for i in range(l-1, -1, -1):
if dominoes[i]=='L':
force2 = l
elif dominoes[i]=='R':
force2 = 0
else:
force2 = max(force2 - 1, 0)
left_force[i] += force2
result = ''
for i in range(l):
if right_force[i] > left_force[i]:
result += 'R'
elif right_force[i] < left_force[i]:
result += 'L'
else:
result += '.'
return result
|
There are N dominoes in a line, and we place each domino vertically upright.
In the beginning, we simultaneously push some of the dominoes either to the left or to the right.
After each second, each domino that is falling to the left pushes the adjacent domino on the left.
Similarly, the dominoes falling to the right push their adjacent dominoes standing on the right.
When a vertical domino has dominoes falling on it from both sides, it stays still due to the balance of the forces.
For the purposes of this question, we will consider that a falling domino expends no additional force to a falling or already fallen domino.
Given a string "S" representing the initial state. S[i] = 'L', if the i-th domino has been pushed to the left; S[i] = 'R', if the i-th domino has been pushed to the right; S[i] = '.', if the i-th domino has not been pushed.
Return a string representing the final state.
Example 1:
Input: ".L.R...LR..L.."
Output: "LL.RR.LLRRLL.."
Example 2:
Input: "RR.L"
Output: "RR.L"
Explanation: The first domino expends no additional force on the second domino.
Note:
0 <= N <= 10^5
String dominoes contains only 'L', 'R' and '.'
|
class Solution:
def pushDominoes(self, dominoes: str) -> str:
forces = [0] * len(dominoes)
max_force = len(dominoes)
force = 0
for i, d in enumerate(dominoes):
if d == 'R':
force = max_force
elif d == 'L': # have to use elif here, not if
force = 0
else:
force = max(0, force - 1)
forces[i] += force
force = 0
for i in range(len(dominoes) - 1, -1, -1):
d = dominoes[i]
if d == 'L':
force = max_force
elif d == 'R':
force = 0
else:
force = max(0, force - 1)
forces[i] -= force
print(forces)
result = ''
for f in forces:
if f == 0:
result += '.'
elif f > 0:
result += 'R'
else:
result += 'L'
return result
# TC: O(N)
# SC: O(N)
|
There are N dominoes in a line, and we place each domino vertically upright.
In the beginning, we simultaneously push some of the dominoes either to the left or to the right.
After each second, each domino that is falling to the left pushes the adjacent domino on the left.
Similarly, the dominoes falling to the right push their adjacent dominoes standing on the right.
When a vertical domino has dominoes falling on it from both sides, it stays still due to the balance of the forces.
For the purposes of this question, we will consider that a falling domino expends no additional force to a falling or already fallen domino.
Given a string "S" representing the initial state. S[i] = 'L', if the i-th domino has been pushed to the left; S[i] = 'R', if the i-th domino has been pushed to the right; S[i] = '.', if the i-th domino has not been pushed.
Return a string representing the final state.
Example 1:
Input: ".L.R...LR..L.."
Output: "LL.RR.LLRRLL.."
Example 2:
Input: "RR.L"
Output: "RR.L"
Explanation: The first domino expends no additional force on the second domino.
Note:
0 <= N <= 10^5
String dominoes contains only 'L', 'R' and '.'
|
class Solution:
def pushDominoes(self, dominoes: str) -> str:
n = len(dominoes)
balance = [0] * len(dominoes)
b = 0
for index,c in enumerate(dominoes):
if c == 'R':
b = n
elif c == 'L':
b = 0
else:
b = max(b - 1, 0)
balance[index] += b
b = 0
for index,c in enumerate(reversed(dominoes)):
index = -index - 1
if c == 'R':
b = 0
elif c == 'L':
b = n
else:
b = max(b - 1, 0)
balance[index] -= b
result = ['.'] * len(dominoes)
for i in range(len(dominoes)):
if dominoes[i] == 'R' or dominoes[i] == 'L':
result[i] = dominoes[i]
elif balance[i] > 0:
result[i] = 'R'
elif balance[i] < 0:
result[i] = 'L'
return ''.join(result)
|
Given an array A of non-negative integers, the array is squareful if for every pair of adjacent elements, their sum is a perfect square.
Return the number of permutations of A that are squareful. Two permutations A1 and A2 differ if and only if there is some index i such that A1[i] != A2[i].
Example 1:
Input: [1,17,8]
Output: 2
Explanation:
[1,8,17] and [17,8,1] are the valid permutations.
Example 2:
Input: [2,2,2]
Output: 1
Note:
1 <= A.length <= 12
0 <= A[i] <= 1e9
|
class Solution:
def numSquarefulPerms(self, A: List[int]) -> int:
A.sort()
self.ans = 0
def check(A, i, path):
return int((A[i] + path[-1])**0.5 + 0.0)**2 == A[i] + path[-1]
def dfs(A, path):
if not A:
self.ans += 1
return
for i in range(len(A)):
if i > 0 and A[i] == A[i - 1]:
continue
if not path or (path and check(A, i, path)):
dfs(A[:i] + A[i + 1:], path + [A[i]])
dfs(A, [])
return self.ans
|
Given an array A of non-negative integers, the array is squareful if for every pair of adjacent elements, their sum is a perfect square.
Return the number of permutations of A that are squareful. Two permutations A1 and A2 differ if and only if there is some index i such that A1[i] != A2[i].
Example 1:
Input: [1,17,8]
Output: 2
Explanation:
[1,8,17] and [17,8,1] are the valid permutations.
Example 2:
Input: [2,2,2]
Output: 1
Note:
1 <= A.length <= 12
0 <= A[i] <= 1e9
|
from copy import copy
class Solution:
def numSquarefulPerms(self, A: List[int]) -> int:
d = dict()
count = dict()
lim = len(A)
blank = dict()
for i in range(0,lim-1):
try:
count[A[i]]+=1
except:
blank[A[i]]=0
count[A[i]]=1
for j in range(i+1,lim):
if ((A[i]+A[j])**.5).is_integer():
try:
d[A[i]].add(A[j])
except:
d[A[i]] = set()
d[A[i]].add(A[j])
try:
d[A[j]].add(A[i])
except:
d[A[j]] = set()
d[A[j]].add(A[i])
try:
count[A[-1]]+=1
except:
count[A[-1]]=1
blank[A[-1]]=0
check = sorted(A)
if d==dict():return 0
f = set()
c = 0
def r(val,ld,l,lth):
if lth==lim:
f.add(tuple(l))
else:
if val in d:
for x in d[val]:
s = copy(ld)
if s[x]<=count[x]:
s[x]+=1
r(x,s,l+[x],lth+1)
for x in set(A):
r(x,blank,[x],1)
for x in f:
if sorted(list(x))==check:c+=1
return c
|
Given an array A of non-negative integers, the array is squareful if for every pair of adjacent elements, their sum is a perfect square.
Return the number of permutations of A that are squareful. Two permutations A1 and A2 differ if and only if there is some index i such that A1[i] != A2[i].
Example 1:
Input: [1,17,8]
Output: 2
Explanation:
[1,8,17] and [17,8,1] are the valid permutations.
Example 2:
Input: [2,2,2]
Output: 1
Note:
1 <= A.length <= 12
0 <= A[i] <= 1e9
|
class Solution:
def numSquarefulPerms(self, A: List[int]) -> int:
def get_valid():
ans = 0
seen = set()
visited = set()
while q:
cur, remaining = q.popleft()
if not remaining and cur not in seen:
ans += 1
for i, n in enumerate(remaining):
sq = (cur[-1] + n) ** .5
if float(int(sq)) == sq:
add = cur + (n,)
remain = remaining[:i] + remaining[i+1:]
if (add, remain) not in visited:
q.append((add, remain))
visited.add((add, remain))
return ans
q = deque()
for i, num in enumerate(A):
q.append(((num, ), tuple(A[:i] + A[i+1:])))
return get_valid()
|
Given an array A of non-negative integers, the array is squareful if for every pair of adjacent elements, their sum is a perfect square.
Return the number of permutations of A that are squareful. Two permutations A1 and A2 differ if and only if there is some index i such that A1[i] != A2[i].
Example 1:
Input: [1,17,8]
Output: 2
Explanation:
[1,8,17] and [17,8,1] are the valid permutations.
Example 2:
Input: [2,2,2]
Output: 1
Note:
1 <= A.length <= 12
0 <= A[i] <= 1e9
|
class Solution:
def numSquarefulPerms(self, A: List[int]) -> int:
c = collections.Counter(A)
cand = {i: {j for j in c if int((i + j)**0.5) ** 2 == i + j} for i in c}
def dfs(x, left=len(A) - 1):
c[x] -= 1
count = sum(dfs(y, left - 1) for y in cand[x] if c[y]) if left else 1
c[x] += 1
return count
return sum(map(dfs, c))
|
Given an array A of non-negative integers, the array is squareful if for every pair of adjacent elements, their sum is a perfect square.
Return the number of permutations of A that are squareful. Two permutations A1 and A2 differ if and only if there is some index i such that A1[i] != A2[i].
Example 1:
Input: [1,17,8]
Output: 2
Explanation:
[1,8,17] and [17,8,1] are the valid permutations.
Example 2:
Input: [2,2,2]
Output: 1
Note:
1 <= A.length <= 12
0 <= A[i] <= 1e9
|
class Solution:
def numSquarefulPerms(self, A: List[int]) -> int:
'''
# graph of indices, works if we don't have duplicate elements
graph = collections.defaultdict(list)
for i in range(len(A)):
for j in range(i+1, len(A)):
if int((A[i]+A[j])**0.5)**2==(A[i]+A[j]):
graph[i] += [j]
graph[j] += [i]
# source node
graph[-1] = [i for i in range(len(A))]
def dfs(node, visited):
if len(visited)==len(A):
return 1
res = 0
for neighbor in graph[node]:
if neighbor in visited:
continue
res += dfs(neighbor, visited|{neighbor})
return res
return dfs(-1, set())
'''
candidates = collections.Counter(A)
graph = {x: [y for y in candidates if int((x+y)**0.5)**2==x+y] for x in candidates}
# source node
graph[-1] = [x for x in candidates]
def dfs(node, node_left):
if node_left==0:
return 1
res = 0
for n in graph[node]:
if candidates[n]==0:
continue
candidates[n] -= 1
res += dfs(n, node_left-1)
candidates[n] += 1
return res
return dfs(-1, len(A))
|
Given an array A of non-negative integers, the array is squareful if for every pair of adjacent elements, their sum is a perfect square.
Return the number of permutations of A that are squareful. Two permutations A1 and A2 differ if and only if there is some index i such that A1[i] != A2[i].
Example 1:
Input: [1,17,8]
Output: 2
Explanation:
[1,8,17] and [17,8,1] are the valid permutations.
Example 2:
Input: [2,2,2]
Output: 1
Note:
1 <= A.length <= 12
0 <= A[i] <= 1e9
|
class Solution:
def numSquarefulPerms(self, A: List[int]) -> int:
#visited = [False] * len(A)
visited = collections.Counter(A)
ans = [0]
self.calc(A, visited, [], ans)
return ans[0]
def calc(self, A, visited, tmp, ans):
if len(tmp) == len(A):
ans[0] += 1
#print(tmp)
for i in list(visited.keys()):
if visited[i] == 0:
continue
visited[i] -= 1
tmp.append(i)
if len(tmp) < 2 or (tmp[-1] + tmp[-2])**(0.5) == int((tmp[-1] + tmp[-2])**(0.5)):
self.calc(A, visited, tmp, ans)
tmp.pop()
visited[i] += 1
|
Given an array A of non-negative integers, the array is squareful if for every pair of adjacent elements, their sum is a perfect square.
Return the number of permutations of A that are squareful. Two permutations A1 and A2 differ if and only if there is some index i such that A1[i] != A2[i].
Example 1:
Input: [1,17,8]
Output: 2
Explanation:
[1,8,17] and [17,8,1] are the valid permutations.
Example 2:
Input: [2,2,2]
Output: 1
Note:
1 <= A.length <= 12
0 <= A[i] <= 1e9
|
class Solution:
def numSquarefulPerms(self, nums: List[int]) -> int:
#nums.sort()
self.ans = 0
def isSquare(v):
x = int(v**0.5)
return x * x == v
def dfs(pos):
if pos >= len(nums):
self.ans += 1
return
used = set()
for i in range(pos, len(nums)):
if nums[i] in used:
continue
used.add(nums[i])
nums[pos], nums[i] = nums[i], nums[pos]
if (pos == 0) or ( pos > 0 and isSquare(nums[pos] + nums[pos-1])):
dfs(pos+1)
nums[pos], nums[i] = nums[i], nums[pos]
dfs(0)
return self.ans
|
Given an array A of non-negative integers, the array is squareful if for every pair of adjacent elements, their sum is a perfect square.
Return the number of permutations of A that are squareful. Two permutations A1 and A2 differ if and only if there is some index i such that A1[i] != A2[i].
Example 1:
Input: [1,17,8]
Output: 2
Explanation:
[1,8,17] and [17,8,1] are the valid permutations.
Example 2:
Input: [2,2,2]
Output: 1
Note:
1 <= A.length <= 12
0 <= A[i] <= 1e9
|
class Solution:
def numSquarefulPerms(self, A: List[int]) -> int:
n = len(A)
A = sorted(A)
# g[i][j] = 1 if A[i], A[j] are squareful
g = [[0] * n for _ in range(n)]
# dp[s][i]: number of ways to reach state s and ends with node i
dp = [[0] * n for _ in range(1 << n)]
for i in range(n):
for j in range(n):
if i == j:
continue
r = int((A[i] + A[j]) ** 0.5)
if r ** 2 == A[i] + A[j]:
g[i][j] = 1
for i in range(n):
if i == 0 or A[i] != A[i - 1]:
dp[(1 << i)][i] = 1
ans = 0
for s in range(1 << n):
for i in range(n):
if not dp[s][i]:
continue
for j in range(n):
if not g[i][j]:
continue
if s & (1 << j):
continue
if j > 0 and not (s & (1 << (j - 1))) and A[j - 1] == A[j]:
continue
dp[s | (1 << j)][j] += dp[s][i]
for i in range(n):
ans += dp[(1 << n) - 1][i]
return ans
|
Given an array A of non-negative integers, the array is squareful if for every pair of adjacent elements, their sum is a perfect square.
Return the number of permutations of A that are squareful. Two permutations A1 and A2 differ if and only if there is some index i such that A1[i] != A2[i].
Example 1:
Input: [1,17,8]
Output: 2
Explanation:
[1,8,17] and [17,8,1] are the valid permutations.
Example 2:
Input: [2,2,2]
Output: 1
Note:
1 <= A.length <= 12
0 <= A[i] <= 1e9
|
# https://zxi.mytechroad.com/blog/searching/leetcode-996-number-of-squareful-arrays/
# g[i][j]: if i and j are squareful
# dp[s][i]: # of ways to reach state s (binary mask of nodes visited) that ends with node i
# dp[s | (1 << j)][j] += dp[s][i] if g[i][j]
# 先对数组排序, 然后计算出所有的 g[i][j]
# for i in range(n) 初始化 dp[(1 << i)][i] = 1, 表示只有一个数字 i 的情况, 每个都是一种
# 如果有多个重复的数字, 只用第一个数字作为开头
# ans = sum(dp[(1 << n) - 1][i])
# O(n^2*2^n) time complexity, O(2^n) space complexity
import math
class Solution:
def numSquarefulPerms(self, A: List[int]) -> int:
n = len(A)
A = sorted(A)
g = [[False] * n for _ in range(n)]
dp = [[0] * n for _ in range(1 << n)]
for i in range(n):
for j in range(n):
if i == j:
continue
if int((A[i] + A[j]) ** 0.5 + 0.5) ** 2 == A[i] + A[j]:
g[i][j] = True
for i in range(n):
if i > 0 and A[i] == A[i - 1]: # For the same numbers, only the first one can be the starting point
continue
dp[1 << i][i] = 1
for s in range(1 << n):
for i in range(n):
if dp[s][i] <= 0: # 如果 dp[s][i] <= 0, 说明没有以 i 结尾的情况, 跳过
continue
for j in range(n): # 尝试让任意一个数字连接在最后面
if not g[i][j] or (s & (1 << j)): # 如果 i, j 不是 squareful 或 j 已经使用过, 跳过
continue
if j > 0 and not (s & (1 << (j - 1))) and A[j] == A[j - 1]: # 出现重复的只使用第一个
continue
dp[s | (1 << j)][j] += dp[s][i]
res = 0
for i in range(n):
res += dp[(1 << n) - 1][i]
return res
|
Given an array A of non-negative integers, the array is squareful if for every pair of adjacent elements, their sum is a perfect square.
Return the number of permutations of A that are squareful. Two permutations A1 and A2 differ if and only if there is some index i such that A1[i] != A2[i].
Example 1:
Input: [1,17,8]
Output: 2
Explanation:
[1,8,17] and [17,8,1] are the valid permutations.
Example 2:
Input: [2,2,2]
Output: 1
Note:
1 <= A.length <= 12
0 <= A[i] <= 1e9
|
import numpy as np
class Solution:
graph = {}
count = {}
def numSquarefulPerms(self, A: List[int]) -> int:
self.graph = {}
self.count = {}
for i in A:
if i in self.count:
self.count[i] += 1
else:
self.count[i] = 1
self.graph[i] = []
for i in self.count:
for j in self.count:
r = int(np.sqrt(i + j))
if r * r == i + j:
self.graph[i].append(j)
ans = 0
L = len(A)
for i in self.graph:
ans += self.dfs(i, L-1)
return ans
def dfs(self, i, L):
self.count[i] -= 1
ans = 1
if L != 0:
ans = 0
for j in self.graph[i]:
if self.count[j] != 0:
ans += self.dfs(j, L - 1)
self.count[i] += 1
return ans
|
Given an array A of non-negative integers, the array is squareful if for every pair of adjacent elements, their sum is a perfect square.
Return the number of permutations of A that are squareful. Two permutations A1 and A2 differ if and only if there is some index i such that A1[i] != A2[i].
Example 1:
Input: [1,17,8]
Output: 2
Explanation:
[1,8,17] and [17,8,1] are the valid permutations.
Example 2:
Input: [2,2,2]
Output: 1
Note:
1 <= A.length <= 12
0 <= A[i] <= 1e9
|
import numpy as np
class Solution:
def numSquarefulPerms(self, A: List[int]) -> int:
N = len(A)
count = collections.Counter(A)
graph = collections.defaultdict(list)
for x in count:
for y in count:
if int((x + y) ** (0.5)) ** 2 == (x + y):
graph[x].append(y)
def dfs(x, todo):
count[x] -= 1
if todo == 0:
ans = 1
else:
ans = 0
for y in graph[x]:
if count[y]:
ans += dfs(y, todo - 1)
count[x] += 1
return ans
return sum(dfs(x, N - 1) for x in count)
|
Given an array A of non-negative integers, the array is squareful if for every pair of adjacent elements, their sum is a perfect square.
Return the number of permutations of A that are squareful. Two permutations A1 and A2 differ if and only if there is some index i such that A1[i] != A2[i].
Example 1:
Input: [1,17,8]
Output: 2
Explanation:
[1,8,17] and [17,8,1] are the valid permutations.
Example 2:
Input: [2,2,2]
Output: 1
Note:
1 <= A.length <= 12
0 <= A[i] <= 1e9
|
import numpy as np
class Solution:
graph = {}
count = {}
def numSquarefulPerms(self, A: List[int]) -> int:
self.graph = {}
self.count = {}
for i in A:
if i in self.count:
self.count[i] += 1
else:
self.count[i] = 1
self.graph[i] = []
for i in self.count:
for j in self.count:
r = int(np.sqrt(i + j))
if r * r == i + j:
self.graph[i].append(j)
ans = 0
L = len(A)
print((self.count))
print((self.graph))
for i in self.graph:
ans += self.dfs(i, L-1)
return ans
def dfs(self, i, L):
self.count[i] -= 1
ans = 1
if L != 0:
ans = 0
for j in self.graph[i]:
if self.count[j] != 0:
ans += self.dfs(j, L - 1)
self.count[i] += 1
return ans
|
Given an array A of non-negative integers, the array is squareful if for every pair of adjacent elements, their sum is a perfect square.
Return the number of permutations of A that are squareful. Two permutations A1 and A2 differ if and only if there is some index i such that A1[i] != A2[i].
Example 1:
Input: [1,17,8]
Output: 2
Explanation:
[1,8,17] and [17,8,1] are the valid permutations.
Example 2:
Input: [2,2,2]
Output: 1
Note:
1 <= A.length <= 12
0 <= A[i] <= 1e9
|
class Solution:
def numSquarefulPerms(self, A: List[int]) -> int:
def edge(x, y):
return int((x + y) ** 0.5) ** 2 == (x + y)
def dfs(x, t):
count[x] -= 1
if t == 0:
ans = 1
else:
ans = 0
for y in graph[x]:
if count[y]:
ans += dfs(y, t - 1)
count[x] += 1
return ans
N = len(A)
count = collections.Counter(A)
graph = collections.defaultdict(list)
for x in count:
for y in count:
if edge(x, y):
graph[x].append(y)
return sum(dfs(x, N - 1) for x in count)
|
Given an array A of non-negative integers, the array is squareful if for every pair of adjacent elements, their sum is a perfect square.
Return the number of permutations of A that are squareful. Two permutations A1 and A2 differ if and only if there is some index i such that A1[i] != A2[i].
Example 1:
Input: [1,17,8]
Output: 2
Explanation:
[1,8,17] and [17,8,1] are the valid permutations.
Example 2:
Input: [2,2,2]
Output: 1
Note:
1 <= A.length <= 12
0 <= A[i] <= 1e9
|
from functools import lru_cache
class Solution:
def numSquarefulPerms(self, A: List[int]) -> int:
def edge(x, y):
r = math.sqrt(x + y)
return int(r) ** 2 == (x + y)
@lru_cache(None)
def dfs(node, seen):
if seen == (1 << N) - 1:
return 1
ans = 0
for n in graph[node]:
nxt = seen | (1 << n)
if nxt == seen:
continue
ans += dfs(n, nxt)
return ans
N = len(A)
count = collections.Counter(A)
graph = [[] for _ in range(N)]
for i in range(N):
for j in range(i + 1, N):
if edge(A[i], A[j]):
graph[i].append(j)
graph[j].append(i)
ans = sum(dfs(i, 1 << i) for i in range(N))
for v in count.values():
ans //= math.factorial(v)
return ans
|
Given an array A of non-negative integers, the array is squareful if for every pair of adjacent elements, their sum is a perfect square.
Return the number of permutations of A that are squareful. Two permutations A1 and A2 differ if and only if there is some index i such that A1[i] != A2[i].
Example 1:
Input: [1,17,8]
Output: 2
Explanation:
[1,8,17] and [17,8,1] are the valid permutations.
Example 2:
Input: [2,2,2]
Output: 1
Note:
1 <= A.length <= 12
0 <= A[i] <= 1e9
|
class Solution:
def numSquarefulPerms(self, A: List[int]) -> int:
import math
def is_not_square(num):
return int(math.sqrt(num) + 0.5) ** 2 != num
memo = {}
def perms(arr):
key = tuple(sorted(arr))
if key in memo: return memo[key]
if len(arr) <= 1: return [arr]
permutations = []
seen = set()
for i in range(len(arr)):
el = arr[i]
rest = arr[:i] + arr[i+1:]
# if all([is_not_square(el+n) for n in rest]): continue
if el not in seen:
sub_perms = perms(rest)
if not sub_perms: continue
for p in sub_perms:
if not is_not_square(el + p[0]):
permutations.append([el] + p)
seen.add(arr[i])
memo[key] = permutations
return permutations
return len(perms(A))
|
Given an array A of non-negative integers, the array is squareful if for every pair of adjacent elements, their sum is a perfect square.
Return the number of permutations of A that are squareful. Two permutations A1 and A2 differ if and only if there is some index i such that A1[i] != A2[i].
Example 1:
Input: [1,17,8]
Output: 2
Explanation:
[1,8,17] and [17,8,1] are the valid permutations.
Example 2:
Input: [2,2,2]
Output: 1
Note:
1 <= A.length <= 12
0 <= A[i] <= 1e9
|
from functools import lru_cache
class Solution:
def numSquarefulPerms(self, A: List[int]) -> int:
N = len(A)
def valid(x,y):
return (math.sqrt(x+y)).is_integer()
graph = [[] for _ in range(N)]
for i,x in enumerate(A):
for j in range(i):
if valid(x,A[j]):
graph[i].append(j)
graph[j].append(i)
# FINDING NO OF HAMILTONIAN PATH
@lru_cache(None)
def dfs(node,visited):
if visited == (1<<N) - 1:
return 1
ans = 0
for val in graph[node]:
if (visited & 1<<val)==0:
ans+= dfs(val,visited | 1<<val)
return ans
ans = sum(dfs(i,1<<i) for i in range(N))
count = collections.Counter(A)
for v in count.values():
ans //= math.factorial(v)
return ans
|
Given an array A of non-negative integers, the array is squareful if for every pair of adjacent elements, their sum is a perfect square.
Return the number of permutations of A that are squareful. Two permutations A1 and A2 differ if and only if there is some index i such that A1[i] != A2[i].
Example 1:
Input: [1,17,8]
Output: 2
Explanation:
[1,8,17] and [17,8,1] are the valid permutations.
Example 2:
Input: [2,2,2]
Output: 1
Note:
1 <= A.length <= 12
0 <= A[i] <= 1e9
|
from functools import lru_cache
class Solution:
def numSquarefulPerms(self, A):
N = len(A)
def edge(x, y):
r = math.sqrt(x+y)
return int(r + 0.5) ** 2 == x+y
graph = [[] for _ in range(len(A))]
for i, x in enumerate(A):
for j in range(i):
if edge(x, A[j]):
graph[i].append(j)
graph[j].append(i)
# find num of hamiltonian paths in graph
@lru_cache(None)
def dfs(node, visited):
if visited == (1 << N) - 1:
return 1
ans = 0
for nei in graph[node]:
if (visited >> nei) & 1 == 0:
ans += dfs(nei, visited | (1 << nei))
return ans
ans = sum(dfs(i, 1<<i) for i in range(N))
count = collections.Counter(A)
for v in count.values():
ans //= math.factorial(v)
return ans
|
Given an array A of non-negative integers, the array is squareful if for every pair of adjacent elements, their sum is a perfect square.
Return the number of permutations of A that are squareful. Two permutations A1 and A2 differ if and only if there is some index i such that A1[i] != A2[i].
Example 1:
Input: [1,17,8]
Output: 2
Explanation:
[1,8,17] and [17,8,1] are the valid permutations.
Example 2:
Input: [2,2,2]
Output: 1
Note:
1 <= A.length <= 12
0 <= A[i] <= 1e9
|
from functools import lru_cache
class Solution:
def numSquarefulPerms(self, A: List[int]) -> int:
N = len(A)
def edge(x, y):
r = math.sqrt(x+y)
return int(r + 0.5) ** 2 == x+y
graph = [[] for _ in range(len(A))]
for i, x in enumerate(A):
for j in range(i):
if edge(x, A[j]):
graph[i].append(j)
graph[j].append(i)
# find num of hamiltonian paths in graph
@lru_cache(None)
def dfs(node, visited):
if visited == (1 << N) - 1:
return 1
ans = 0
for nei in graph[node]:
if (visited >> nei) & 1 == 0:
ans += dfs(nei, visited | (1 << nei))
return ans
ans = sum(dfs(i, 1<<i) for i in range(N))
count = collections.Counter(A)
for v in count.values():
ans //= math.factorial(v)
return ans
|
Given an array A of non-negative integers, the array is squareful if for every pair of adjacent elements, their sum is a perfect square.
Return the number of permutations of A that are squareful. Two permutations A1 and A2 differ if and only if there is some index i such that A1[i] != A2[i].
Example 1:
Input: [1,17,8]
Output: 2
Explanation:
[1,8,17] and [17,8,1] are the valid permutations.
Example 2:
Input: [2,2,2]
Output: 1
Note:
1 <= A.length <= 12
0 <= A[i] <= 1e9
|
class Solution:
def numSquarefulPerms(self, A: List[int]) -> int:
N = len(A)
def edge(x, y):
r = math.sqrt(x+y)
return int(r + 0.5) ** 2 == x+y
graph = [[] for _ in range(len(A))]
for i, x in enumerate(A):
for j in range(i):
if edge(x, A[j]):
graph[i].append(j)
graph[j].append(i)
# find num of hamiltonian paths in graph
@lru_cache(None)
def dfs(node, visited):
if visited == (1 << N) - 1:
return 1
ans = 0
for nei in graph[node]:
if (visited >> nei) & 1 == 0:
ans += dfs(nei, visited | (1 << nei))
return ans
ans = sum(dfs(i, 1<<i) for i in range(N))
count = collections.Counter(A)
for v in count.values():
ans //= math.factorial(v)
return ans
|
Given an array A of non-negative integers, the array is squareful if for every pair of adjacent elements, their sum is a perfect square.
Return the number of permutations of A that are squareful. Two permutations A1 and A2 differ if and only if there is some index i such that A1[i] != A2[i].
Example 1:
Input: [1,17,8]
Output: 2
Explanation:
[1,8,17] and [17,8,1] are the valid permutations.
Example 2:
Input: [2,2,2]
Output: 1
Note:
1 <= A.length <= 12
0 <= A[i] <= 1e9
|
def getPermutations(array):
ans = set()
def helper(arr,i,ans):
if i==len(arr)-1:
ans.add(tuple(arr))
return
for j in range(i,len(arr)):
if not (arr[i]==arr[j] and i!=j):
test = (i<=1) or (((arr[i-1]+arr[i-2])**0.5)==int((arr[i-1]+arr[i-2])**0.5))
swap(arr,i,j)
if (test):
helper(arr,i+1,ans)
swap(arr,i,j)
def swap(arr,i,j):
arr[i],arr[j]=arr[j],arr[i]
helper(array,0,ans)
return ans
class Solution:
def numSquarefulPerms(self, A: List[int]) -> int:
va = getPermutations(A)
valid = 0
# print(va)
for a in va:
isValid = True
# print(a)
for idx in range(1,len(a)):
if ((a[idx]+a[idx-1])**0.5)!=int((a[idx]+a[idx-1])**0.5):
# print(a,idx)
isValid = False
break
if isValid:
# print(a)
valid+=1
# print(valid)
return valid
|
Given an array A of non-negative integers, the array is squareful if for every pair of adjacent elements, their sum is a perfect square.
Return the number of permutations of A that are squareful. Two permutations A1 and A2 differ if and only if there is some index i such that A1[i] != A2[i].
Example 1:
Input: [1,17,8]
Output: 2
Explanation:
[1,8,17] and [17,8,1] are the valid permutations.
Example 2:
Input: [2,2,2]
Output: 1
Note:
1 <= A.length <= 12
0 <= A[i] <= 1e9
|
from functools import lru_cache
class Solution:
def numSquarefulPerms(self, A):
N = len(A)
def edge(x, y):
r = math.sqrt(x+y)
return int(r + 0.5) ** 2 == x+y
graph = [[] for _ in range(len(A))]
for i, x in enumerate(A):
for j in range(i):
if edge(x, A[j]):
graph[i].append(j)
graph[j].append(i)
# find num of hamiltonian paths in graph
@lru_cache(None)
def dfs(node, visited):
if visited == (1 << N) - 1:
return 1
ans = 0
for nei in graph[node]:
if (visited >> nei) & 1 == 0:
ans += dfs(nei, visited | (1 << nei))
return ans
ans = sum(dfs(i, 1<<i) for i in range(N))
count = collections.Counter(A)
for v in count.values():
ans //= math.factorial(v)
return ans
|
Given an array A of non-negative integers, the array is squareful if for every pair of adjacent elements, their sum is a perfect square.
Return the number of permutations of A that are squareful. Two permutations A1 and A2 differ if and only if there is some index i such that A1[i] != A2[i].
Example 1:
Input: [1,17,8]
Output: 2
Explanation:
[1,8,17] and [17,8,1] are the valid permutations.
Example 2:
Input: [2,2,2]
Output: 1
Note:
1 <= A.length <= 12
0 <= A[i] <= 1e9
|
class Solution:
def numSquarefulPerms(self, A):
A.sort()
N = len(A)
graph = [[0] * N for _ in range(N)]
for i in range(N):
for j in range(N):
if i==j: continue
if int((A[i]+A[j])**0.5)**2==(A[i]+A[j]):
graph[i][j]=1
graph[j][i]=1
dp=[[0]*N for i in range(1<<N)]
for i in range(N):
dp[1<<i][i]=1
for s in range(1<<N):
for i in range(N):
if not dp[s][i]: continue
for j in range(N):
if not graph[i][j]: continue
if s&(1<<j): continue
if j>0 and s&(1<<(j-1)) and A[j]==A[j-1]:continue
dp[s|(1<<j)][j]+=dp[s][i]
ans=0
for i in range(N):
ans+=dp[-1][i]
return ans
|
Given an array A of non-negative integers, the array is squareful if for every pair of adjacent elements, their sum is a perfect square.
Return the number of permutations of A that are squareful. Two permutations A1 and A2 differ if and only if there is some index i such that A1[i] != A2[i].
Example 1:
Input: [1,17,8]
Output: 2
Explanation:
[1,8,17] and [17,8,1] are the valid permutations.
Example 2:
Input: [2,2,2]
Output: 1
Note:
1 <= A.length <= 12
0 <= A[i] <= 1e9
|
from collections import Counter
class Solution:
def numSquarefulPerms(self, A: List[int]) -> int:
counts = Counter(A)
graph = {x: [] for x in counts}
for x in counts:
for y in counts:
r = int((x + y) ** 0.5 + 0.5)
if r * r == x + y:
graph[x].append(y)
def dfs(x, todo):
counts[x] -= 1
if todo == 0:
res = 1
else:
res = 0
for y in graph[x]:
if counts[y] > 0:
res += dfs(y, todo - 1)
counts[x] += 1
return res
return sum(dfs(x, len(A) - 1) for x in counts)
|
Given an array A of non-negative integers, the array is squareful if for every pair of adjacent elements, their sum is a perfect square.
Return the number of permutations of A that are squareful. Two permutations A1 and A2 differ if and only if there is some index i such that A1[i] != A2[i].
Example 1:
Input: [1,17,8]
Output: 2
Explanation:
[1,8,17] and [17,8,1] are the valid permutations.
Example 2:
Input: [2,2,2]
Output: 1
Note:
1 <= A.length <= 12
0 <= A[i] <= 1e9
|
from collections import Counter
from functools import lru_cache
import math
class Solution:
def numSquarefulPerms(self, A: List[int]) -> int:
# Backtracking
# Time complexity: O(N^N)
# Space complexity: O(N)
# N = len(A)
# count = Counter(A)
# graph = {x: [] for x in count}
# for x in count:
# for y in count:
# if int((x + y) ** .5 + 0.5) ** 2 == x + y:
# graph[x].append(y)
# def dfs(x, todo):
# count[x] -= 1
# if todo == 0:
# ans = 1
# else:
# ans = 0
# for y in graph[x]:
# if count[y]:
# ans += dfs(y, todo - 1)
# count[x] += 1
# return ans
# return sum(dfs(x, len(A) - 1) for x in count)
# Dynamic Programming
# Time complexity: O(N^2 x 2^N) = O(sum_{k=1}^{N} C_N^K x C_k^2)
# Space complexity: O(N x 2^N)
N = len(A)
def edge(x, y):
r = math.sqrt(x + y)
return int(r + 0.5) ** 2 == x + y
graph = [[] for _ in range(len(A))]
for i, x in enumerate(A):
for j in range(i):
if edge(x, A[j]):
graph[i].append(j)
graph[j].append(i)
# find num of hamiltonian paths in graph
@lru_cache(None)
def dfs(node, visited):
if visited == (1 << N) - 1:
return 1
ans = 0
for nei in graph[node]:
if (visited >> nei) & 1 == 0:
ans += dfs(nei, visited | 1 << nei)
return ans
ans = sum(dfs(i, 1 << i) for i in range(N))
count = Counter(A)
for v in list(count.values()):
ans //= math.factorial(v)
return ans
# c = Counter(A)
# cand = {i: {j for j in c if int((i+j)**.5) ** 2 == i + j} for i in c}
# self.res = 0
# def dfs(x, left=len(A)-1):
# c[x] -= 1
# if left == 0:
# self.res += 1
# for y in cand[x]:
# if c[y]:
# dfs(y, left - 1)
# c[x] += 1
# for x in c: dfs(x)
# return self.res
# def backtrack(i, A):
# if i > 1:
# val = A[i - 2] + A[i - 1]
# is_square = math.sqrt(val) == math.floor(math.sqrt(val))
# if not is_square:
# return
# if i == len(A):
# output.append(A)
# return
# for j in range(i, len(A)):
# A[i], A[j] = A[j], A[i]
# search = (i, A[i], tuple(A[:i]))
# if search not in seen:
# seen.add(search)
# backtrack(i + 1, A)
# A[i], A[j] = A[j], A[i]
# output, seen = [], set()
# backtrack(0, A)
# return len(output)
|
Given an array A of non-negative integers, the array is squareful if for every pair of adjacent elements, their sum is a perfect square.
Return the number of permutations of A that are squareful. Two permutations A1 and A2 differ if and only if there is some index i such that A1[i] != A2[i].
Example 1:
Input: [1,17,8]
Output: 2
Explanation:
[1,8,17] and [17,8,1] are the valid permutations.
Example 2:
Input: [2,2,2]
Output: 1
Note:
1 <= A.length <= 12
0 <= A[i] <= 1e9
|
class Solution:
def dfs(self, pos):
if pos==self.n:
self.ans += 1
return
last = None
for i, val in enumerate(self.a):
if self.usable[i]:
if val == last:
continue
if pos-1 >= 0 and (val + self.rec[pos-1]) not in self.square:
continue
self.usable[i] = False
self.rec[pos] = val
self.dfs(pos + 1)
self.usable[i] = True
last = val
def numSquarefulPerms(self, A: List[int]) -> int:
self.a = sorted(A)
self.square=set()
i = 0 # not 1
while i*i <= self.a[-1]*2:
self.square.add(i*i)
i += 1
#print(self.square)
self.ans = 0
self.n = len(self.a)
self.usable = [True]*self.n
self.rec = [None]*self.n
self.dfs(0)
return self.ans
|
Given an array A of non-negative integers, the array is squareful if for every pair of adjacent elements, their sum is a perfect square.
Return the number of permutations of A that are squareful. Two permutations A1 and A2 differ if and only if there is some index i such that A1[i] != A2[i].
Example 1:
Input: [1,17,8]
Output: 2
Explanation:
[1,8,17] and [17,8,1] are the valid permutations.
Example 2:
Input: [2,2,2]
Output: 1
Note:
1 <= A.length <= 12
0 <= A[i] <= 1e9
|
class Solution:
def numSquarefulPerms(self, A: List[int]) -> int:
d = defaultdict(int)
res = 0
ps = {}
i = 0
while i*i <= 2*max(A):
ps[i*i]=True
i += 1
def ok(x):
return x in ps
def solve(x):
nonlocal res
# takes some number X and multiset D. Returns answer of the problem for numbers in D such that first number is X
if not len(d):
res += 1
return
for k in list(d.keys()):
if not ok(x + k): continue
d[k] -= 1
if d[k] == 0: del d[k]
solve(k)
d[k] += 1
for x in A: d[x] += 1
for k in list(d.keys()):
d[k] -= 1
if not d[k]: del d[k]
solve(k)
d[k] += 1
return res
|
Given an array A of non-negative integers, the array is squareful if for every pair of adjacent elements, their sum is a perfect square.
Return the number of permutations of A that are squareful. Two permutations A1 and A2 differ if and only if there is some index i such that A1[i] != A2[i].
Example 1:
Input: [1,17,8]
Output: 2
Explanation:
[1,8,17] and [17,8,1] are the valid permutations.
Example 2:
Input: [2,2,2]
Output: 1
Note:
1 <= A.length <= 12
0 <= A[i] <= 1e9
|
from typing import List
from collections import defaultdict
class Solution:
def helper(self, last_num, used, partners, index):
if index == len(used):
return 1
total = 0
# print(partners, partners[last_num])
for partner, partner_list in partners[last_num].items():
for partner_index in partner_list:
if not used[partner_index]:
used[partner_index] = True
total += self.helper(partner, used, partners, index+1)
used[partner_index] = False
break
return total
def numSquarefulPerms(self, A: List[int]) -> int:
squares = set()
i = 0
partners = defaultdict(lambda: defaultdict(set))
while i * i <= 200000000:
squares.add(i*i)
i += 1
for i in range(len(A)):
for j in range(i+1, len(A), 1):
if A[i] + A[j] in squares:
partners[A[i]][A[j]].add(j)
partners[A[j]][A[i]].add(i)
unique_nums = dict()
for i, num in enumerate(A):
unique_nums[num] = i
used = [False for _ in A]
total = 0
for num, i in unique_nums.items():
used[i] = True
total += self.helper(num, used, partners, 1)
used[i] = False
return total
|
Given an array A of non-negative integers, the array is squareful if for every pair of adjacent elements, their sum is a perfect square.
Return the number of permutations of A that are squareful. Two permutations A1 and A2 differ if and only if there is some index i such that A1[i] != A2[i].
Example 1:
Input: [1,17,8]
Output: 2
Explanation:
[1,8,17] and [17,8,1] are the valid permutations.
Example 2:
Input: [2,2,2]
Output: 1
Note:
1 <= A.length <= 12
0 <= A[i] <= 1e9
|
class Solution:
def numSquarefulPerms(self, A: List[int]) -> int:
A.sort()
self.ans = 0
def check(A, i, path):
return int((A[i] + path[-1])**0.5 + 0.0)**2 == A[i] + path[-1]
def dfs(A, path):
if len(A) == 0:
self.ans += 1
return
for i in range(len(A)):
if i > 0 and A[i] == A[i - 1]:
continue
if len(path) == 0 or (len(path) > 0 and check(A, i, path)):
dfs(A[:i] + A[i + 1:], path + [A[i]])
dfs(A, [])
return self.ans
|
Given an array A of non-negative integers, the array is squareful if for every pair of adjacent elements, their sum is a perfect square.
Return the number of permutations of A that are squareful. Two permutations A1 and A2 differ if and only if there is some index i such that A1[i] != A2[i].
Example 1:
Input: [1,17,8]
Output: 2
Explanation:
[1,8,17] and [17,8,1] are the valid permutations.
Example 2:
Input: [2,2,2]
Output: 1
Note:
1 <= A.length <= 12
0 <= A[i] <= 1e9
|
class Solution:
def numSquarefulPerms(self, A: List[int]) -> int:
def edge(x, y):
return int((x + y) ** 0.5) ** 2 == (x + y)
def dfs(x, t):
count[x] -= 1
if t == 0:
ans = 1
else:
ans = 0
for y in graph[x]:
if count[y]:
ans += dfs(y, t - 1)
count[x] += 1
return ans
N = len(A)
count = collections.Counter(A)
graph = collections.defaultdict(list)
for x in count:
for y in count:
if edge(x, y):
graph[x].append(y)
return sum(dfs(x, N - 1) for x in count)
|
Given an array A of non-negative integers, the array is squareful if for every pair of adjacent elements, their sum is a perfect square.
Return the number of permutations of A that are squareful. Two permutations A1 and A2 differ if and only if there is some index i such that A1[i] != A2[i].
Example 1:
Input: [1,17,8]
Output: 2
Explanation:
[1,8,17] and [17,8,1] are the valid permutations.
Example 2:
Input: [2,2,2]
Output: 1
Note:
1 <= A.length <= 12
0 <= A[i] <= 1e9
|
class Solution:
def numSquarefulPerms(self, A: List[int]) -> int:
A.sort()
n = len(A)
visited = [False] * n
res = []
self.count = 0
def dfs(curr):
if len(curr) == n:
self.count += 1
return
for i in range(n):
if visited[i]: continue
if i > 0 and A[i] == A[i - 1] and not visited[i - 1]: continue
if len(curr) > 0 and (int((curr[-1] + A[i]) ** 0.5))**2 != curr[-1] + A[i]: continue
visited[i] = True
dfs(curr + [A[i]])
visited[i] = False
dfs([])
return self.count
|
Given an array A of non-negative integers, the array is squareful if for every pair of adjacent elements, their sum is a perfect square.
Return the number of permutations of A that are squareful. Two permutations A1 and A2 differ if and only if there is some index i such that A1[i] != A2[i].
Example 1:
Input: [1,17,8]
Output: 2
Explanation:
[1,8,17] and [17,8,1] are the valid permutations.
Example 2:
Input: [2,2,2]
Output: 1
Note:
1 <= A.length <= 12
0 <= A[i] <= 1e9
|
from math import sqrt
class Solution:
def numSquarefulPerms(self, A: List[int]) -> int:
return self.backtrack(A, 0, set())
def isPerfect(self, num):
return int(sqrt(num))**2 == num
def backtrack(self, permutation, j, seen):
permutation_tuple = (j,) + tuple(permutation)
if permutation_tuple in seen: return 0
seen.add(permutation_tuple)
if j == len(permutation):
return 1
total = 0
for i in range(j, len(permutation)):
self.swap(permutation, i, j)
if j == 0 or self.isPerfect(permutation[j] + permutation[j-1]):
total += self.backtrack(permutation, j+1, seen)
self.swap(permutation, i, j)
return total
def swap(self, array, i, j):
array[i], array[j] = array[j], array[i]
|
Given an array A of non-negative integers, the array is squareful if for every pair of adjacent elements, their sum is a perfect square.
Return the number of permutations of A that are squareful. Two permutations A1 and A2 differ if and only if there is some index i such that A1[i] != A2[i].
Example 1:
Input: [1,17,8]
Output: 2
Explanation:
[1,8,17] and [17,8,1] are the valid permutations.
Example 2:
Input: [2,2,2]
Output: 1
Note:
1 <= A.length <= 12
0 <= A[i] <= 1e9
|
class Solution:
def numSquarefulPerms(self, A: List[int]) -> int:
count ={}
for i in A:
count[i]=count.get(i,0)+1
graph = {x: [] for x in A}
for x in count:
for y in count:
if int((x + y) ** 0.5 + 0.5) ** 2 == x + y:
graph[x].append(y)
def dfs(x, todo):
count[x] -= 1
if todo == 0:
ans = 1
else:
ans = 0
for y in graph[x]:
if count[y]:
ans += dfs(y, todo - 1)
count[x] += 1
return ans
return sum(dfs(x, len(A) - 1) for x in count)
|
Given an array A of non-negative integers, the array is squareful if for every pair of adjacent elements, their sum is a perfect square.
Return the number of permutations of A that are squareful. Two permutations A1 and A2 differ if and only if there is some index i such that A1[i] != A2[i].
Example 1:
Input: [1,17,8]
Output: 2
Explanation:
[1,8,17] and [17,8,1] are the valid permutations.
Example 2:
Input: [2,2,2]
Output: 1
Note:
1 <= A.length <= 12
0 <= A[i] <= 1e9
|
class Solution:
def numSquarefulPerms(self, A: List[int]) -> int:
c = {}
for i in A:
c[i]=c.get(i,0)+1
cand = {i: [j for j in c if int((i + j)**0.5) ** 2 == i + j] for i in c}
def dfs(x, left=len(A) - 1):
c[x] -= 1
count = sum(dfs(y, left - 1) for y in cand[x] if c[y]) if left else 1
c[x] += 1
return count
return sum(map(dfs, c))
|
Given an array A of 0s and 1s, we may change up to K values from 0 to 1.
Return the length of the longest (contiguous) subarray that contains only 1s.
Example 1:
Input: A = [1,1,1,0,0,0,1,1,1,1,0], K = 2
Output: 6
Explanation:
[1,1,1,0,0,1,1,1,1,1,1]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
Example 2:
Input: A = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], K = 3
Output: 10
Explanation:
[0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
Note:
1 <= A.length <= 20000
0 <= K <= A.length
A[i] is 0 or 1
|
class Solution:
def longestOnes(self, A: List[int], K: int) -> int:
hulu = []
cnt = 0
num = A[0]
for x in A:
if x == num:
cnt += 1
else:
hulu.append([num,cnt])
cnt = 1
num = x
if cnt>0:
hulu.append([num,cnt])
# print(hulu)
output = 0
if A[0] == 1:
start = 0
else:
start = 1
if len(hulu)<2:
return min(K,len(A))
end = start
usage = 0
ones = hulu[start][1]
while end+2<len(hulu) and usage+hulu[end+1][1]<=K:
usage += hulu[end+1][1]
ones += hulu[end+2][1]
end += 2
output = ones+K
# print([start,end,usage,ones])
start += 2
while start<len(hulu):
ones -= hulu[start-2][1]
usage -= hulu[start-1][1]
if start>end:
end = start
ones = hulu[start][1]
usage = 0
while end+2<len(hulu) and usage+hulu[end+1][1]<=K:
usage += hulu[end+1][1]
ones += hulu[end+2][1]
end += 2
# print([start,end,usage,ones])
output = max(output,ones+K)
start += 2
return min(output,len(A))
|
Given an array A of 0s and 1s, we may change up to K values from 0 to 1.
Return the length of the longest (contiguous) subarray that contains only 1s.
Example 1:
Input: A = [1,1,1,0,0,0,1,1,1,1,0], K = 2
Output: 6
Explanation:
[1,1,1,0,0,1,1,1,1,1,1]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
Example 2:
Input: A = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], K = 3
Output: 10
Explanation:
[0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
Note:
1 <= A.length <= 20000
0 <= K <= A.length
A[i] is 0 or 1
|
class Solution:
def longestOnes(self, A: List[int], K: int) -> int:
if len(A) - sum(A) <= K:
return len(A)
left = right = 0
for right in range(len(A)):
if A[right] == 0:
K-=1
if K < 0:
if A[left] == 0:
K+=1
left += 1
return right-left + 1
|
Given an array A of 0s and 1s, we may change up to K values from 0 to 1.
Return the length of the longest (contiguous) subarray that contains only 1s.
Example 1:
Input: A = [1,1,1,0,0,0,1,1,1,1,0], K = 2
Output: 6
Explanation:
[1,1,1,0,0,1,1,1,1,1,1]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
Example 2:
Input: A = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], K = 3
Output: 10
Explanation:
[0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
Note:
1 <= A.length <= 20000
0 <= K <= A.length
A[i] is 0 or 1
|
'''
[1,1,1,0,0,0,1,1,1,1,0]
i
j
'''
class Solution:
def longestOnes(self, A: List[int], K: int) -> int:
left,right=0,0
alen=len(A)
while right < alen:
if A[right] == 0:
K-=1
if K < 0:
if A[left] == 0:
K+=1
left+=1
right+=1
return right - left
|
Given an array A of 0s and 1s, we may change up to K values from 0 to 1.
Return the length of the longest (contiguous) subarray that contains only 1s.
Example 1:
Input: A = [1,1,1,0,0,0,1,1,1,1,0], K = 2
Output: 6
Explanation:
[1,1,1,0,0,1,1,1,1,1,1]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
Example 2:
Input: A = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], K = 3
Output: 10
Explanation:
[0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
Note:
1 <= A.length <= 20000
0 <= K <= A.length
A[i] is 0 or 1
|
class Solution:
def longestOnes(self, A: List[int], K: int) -> int:
window_start, max_length, max_ones_count = 0, 0, 0
# Try to extend the range [window_start, window_end]
for window_end in range(len(A)):
if A[window_end] == 1:
max_ones_count += 1
# Current window size is from window_start to window_end, overall we have a maximum of 1s
# repeating 'max_ones_count' times, this means we can have a window with 'max_ones_count' 1s
# and the remaining are 0s which should replace with 1s.
# now, if the remaining 1s are more than 'k', it is the time to shrink the window as we
# are not allowed to replace more than 'k' 0s
if (window_end - window_start + 1 - max_ones_count) > K:
if A[window_start] == 1:
max_ones_count -= 1
window_start += 1
max_length = max(max_length, window_end - window_start + 1)
return max_length
|
Given an array A of 0s and 1s, we may change up to K values from 0 to 1.
Return the length of the longest (contiguous) subarray that contains only 1s.
Example 1:
Input: A = [1,1,1,0,0,0,1,1,1,1,0], K = 2
Output: 6
Explanation:
[1,1,1,0,0,1,1,1,1,1,1]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
Example 2:
Input: A = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], K = 3
Output: 10
Explanation:
[0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
Note:
1 <= A.length <= 20000
0 <= K <= A.length
A[i] is 0 or 1
|
class Solution:
def longestOnes(self, A: List[int], K: int) -> int:
i,j,count,res = 0,0, 0,0
while j<len(A):
if A[j]==0:
count+=1
while count>K:
if A[i]==0:
count-=1
i+=1
res= max(res, j-i+1)
j+=1
return res
|
Given an array A of 0s and 1s, we may change up to K values from 0 to 1.
Return the length of the longest (contiguous) subarray that contains only 1s.
Example 1:
Input: A = [1,1,1,0,0,0,1,1,1,1,0], K = 2
Output: 6
Explanation:
[1,1,1,0,0,1,1,1,1,1,1]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
Example 2:
Input: A = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], K = 3
Output: 10
Explanation:
[0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
Note:
1 <= A.length <= 20000
0 <= K <= A.length
A[i] is 0 or 1
|
class Solution:
def longestOnes(self, A: List[int], K: int) -> int:
start, end = 0, 0
max_len = 0
numzeros = 0
while end < len(A):
if A[end] == 0:
numzeros += 1
while numzeros > K:
# shrink window
if A[start] == 0:
numzeros -= 1
start += 1
max_len = max(max_len, end - start + 1)
end += 1
return max_len
|
Given an array A of 0s and 1s, we may change up to K values from 0 to 1.
Return the length of the longest (contiguous) subarray that contains only 1s.
Example 1:
Input: A = [1,1,1,0,0,0,1,1,1,1,0], K = 2
Output: 6
Explanation:
[1,1,1,0,0,1,1,1,1,1,1]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
Example 2:
Input: A = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], K = 3
Output: 10
Explanation:
[0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
Note:
1 <= A.length <= 20000
0 <= K <= A.length
A[i] is 0 or 1
|
class Solution:
def longestOnes(self, A: List[int], K: int) -> int:
res = 0
start, end = 0, 0
cnt = 0
while end < len(A) and start < len(A):
if A[end] == 1:
res = max(res, end - start + 1)
end += 1
elif A[end] == 0 and cnt < K:
res = max(res, end - start + 1)
cnt += 1
end += 1
else:
if A[start] == 0 and K > 0:
cnt -= 1
start += 1
if start > end:
end = start
return res
|
Given an array A of 0s and 1s, we may change up to K values from 0 to 1.
Return the length of the longest (contiguous) subarray that contains only 1s.
Example 1:
Input: A = [1,1,1,0,0,0,1,1,1,1,0], K = 2
Output: 6
Explanation:
[1,1,1,0,0,1,1,1,1,1,1]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
Example 2:
Input: A = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], K = 3
Output: 10
Explanation:
[0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
Note:
1 <= A.length <= 20000
0 <= K <= A.length
A[i] is 0 or 1
|
class Solution:
def longestOnes(self, A: List[int], K: int) -> int:
#brute force, linear scan NAIVE APPROACH
#start with the largest size and move down, time limit exceeded
'''
for size in range(len(A)-1, -1, -1):
i = 0
j = i+size
count = 0
for ind in range(i, j+1):
if A[ind] == 0:
count += 1
while j < len(A):
if count <= K:
return size+1
else:
if A[i] == 0: count -= 1
if j < len(A)-1 and A[j+1] == 0: count += 1
j += 1
i += 1
return 0
'''
#use dynamic variant of sliding window technique
maxConsecutiveOnes = 0
windowStart = 0
currZeroes = 0
#iterate through the array linearly and see if the number of 0s is <= K
for windowEnd in range(len(A)):
if A[windowEnd] == 0:
currZeroes += 1
#shrinks window
while currZeroes > K:
if A[windowStart] == 0:
currZeroes -= 1
windowStart += 1
maxConsecutiveOnes = max(maxConsecutiveOnes, windowEnd - windowStart + 1)
return maxConsecutiveOnes
|
Given an array A of 0s and 1s, we may change up to K values from 0 to 1.
Return the length of the longest (contiguous) subarray that contains only 1s.
Example 1:
Input: A = [1,1,1,0,0,0,1,1,1,1,0], K = 2
Output: 6
Explanation:
[1,1,1,0,0,1,1,1,1,1,1]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
Example 2:
Input: A = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], K = 3
Output: 10
Explanation:
[0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
Note:
1 <= A.length <= 20000
0 <= K <= A.length
A[i] is 0 or 1
|
class Solution:
def longestOnes(self, A: List[int], K: int) -> int:
left=0
right=0
for right in range(len(A)):
if A[right]==0:
K-=1
if K<0:
if A[left]==0:
K+=1
left+=1
return right -left +1
|
Given an array A of 0s and 1s, we may change up to K values from 0 to 1.
Return the length of the longest (contiguous) subarray that contains only 1s.
Example 1:
Input: A = [1,1,1,0,0,0,1,1,1,1,0], K = 2
Output: 6
Explanation:
[1,1,1,0,0,1,1,1,1,1,1]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
Example 2:
Input: A = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], K = 3
Output: 10
Explanation:
[0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
Note:
1 <= A.length <= 20000
0 <= K <= A.length
A[i] is 0 or 1
|
class Solution:
def longestOnes(self, arr: List[int], K: int) -> int:
left = 0
for right in range(len(arr)):
K -= 1 - arr[right]
if K < 0:
K += 1 - arr[left]
left += 1
return right - left + 1
|
Given an array A of 0s and 1s, we may change up to K values from 0 to 1.
Return the length of the longest (contiguous) subarray that contains only 1s.
Example 1:
Input: A = [1,1,1,0,0,0,1,1,1,1,0], K = 2
Output: 6
Explanation:
[1,1,1,0,0,1,1,1,1,1,1]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
Example 2:
Input: A = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], K = 3
Output: 10
Explanation:
[0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
Note:
1 <= A.length <= 20000
0 <= K <= A.length
A[i] is 0 or 1
|
class Solution:
def longestOnes(self, A: List[int], k: int) -> int:
leftPtr=0
rightPtr=0
windowSize=[]
while rightPtr<=len(A)-1:
if A[rightPtr]==0:
k-=1
if k<0:
if A[leftPtr]==0:
k+=1
leftPtr+=1
rightPtr+=1
return rightPtr-leftPtr
|
Given an array A of 0s and 1s, we may change up to K values from 0 to 1.
Return the length of the longest (contiguous) subarray that contains only 1s.
Example 1:
Input: A = [1,1,1,0,0,0,1,1,1,1,0], K = 2
Output: 6
Explanation:
[1,1,1,0,0,1,1,1,1,1,1]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
Example 2:
Input: A = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], K = 3
Output: 10
Explanation:
[0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
Note:
1 <= A.length <= 20000
0 <= K <= A.length
A[i] is 0 or 1
|
class Solution:
def longestOnes(self, A: List[int], K: int) -> int:
left = 0
for right in range(len(A)):
K -= int(A[right] == 0)
if K < 0:
K += 1 - A[left]
left += 1
return right - left + 1
|
Given an array A of 0s and 1s, we may change up to K values from 0 to 1.
Return the length of the longest (contiguous) subarray that contains only 1s.
Example 1:
Input: A = [1,1,1,0,0,0,1,1,1,1,0], K = 2
Output: 6
Explanation:
[1,1,1,0,0,1,1,1,1,1,1]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
Example 2:
Input: A = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], K = 3
Output: 10
Explanation:
[0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
Note:
1 <= A.length <= 20000
0 <= K <= A.length
A[i] is 0 or 1
|
class Solution:
def longestOnes(self, A: List[int], K: int) -> int:
start = 0
end = 0
l = len(A)
count = 0
max_len = 0
while end < l:
# print(start, end)
if A[end] == 1:
max_len = max(max_len, end-start+1)
end = end + 1
else:
if count < K:
max_len = max(max_len, end-start +1)
count = count+1
end = end + 1
else:
while start <= end and count >= K:
if A[start] == 0:
count = count -1
start = start + 1
return max_len
|
Given an array A of 0s and 1s, we may change up to K values from 0 to 1.
Return the length of the longest (contiguous) subarray that contains only 1s.
Example 1:
Input: A = [1,1,1,0,0,0,1,1,1,1,0], K = 2
Output: 6
Explanation:
[1,1,1,0,0,1,1,1,1,1,1]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
Example 2:
Input: A = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], K = 3
Output: 10
Explanation:
[0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
Note:
1 <= A.length <= 20000
0 <= K <= A.length
A[i] is 0 or 1
|
class Solution:
def longestOnes(self, A: List[int], K: int) -> int:
left = 0
for right in range(len(A)):
# If we included a zero in the window we reduce the value of K.
# Since K is the maximum zeros allowed in a window.
K -= (1 - A[right])
# A negative K denotes we have consumed all allowed flips and window has
# more than allowed zeros, thus increment left pointer by 1 to keep the window size same.
if K < 0:
# If the left element to be thrown out is zero we increase K.
K += 1 - A[left]
left += 1
return right - left + 1
|
Given an array A of 0s and 1s, we may change up to K values from 0 to 1.
Return the length of the longest (contiguous) subarray that contains only 1s.
Example 1:
Input: A = [1,1,1,0,0,0,1,1,1,1,0], K = 2
Output: 6
Explanation:
[1,1,1,0,0,1,1,1,1,1,1]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
Example 2:
Input: A = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], K = 3
Output: 10
Explanation:
[0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
Note:
1 <= A.length <= 20000
0 <= K <= A.length
A[i] is 0 or 1
|
def solve(arr,n,k):
prefix=[0]
for i in range(0,n):
if(arr[i]==0):
prefix.append(prefix[-1]+1)
else:
prefix.append(prefix[-1])
low=0
high=n+1
ans=0
while(low<high):
f=0
mid=low+(high-low)//2
for i in range(mid,n+1):
if(prefix[i]-prefix[i-mid]<=k):
ans=max(ans,mid)
f=1
if(f==1):
low=mid+1
else:
high=mid
return ans
class Solution:
def longestOnes(self, A: List[int], K: int) -> int:
return solve(A,len(A),K)
|
Given an array A of 0s and 1s, we may change up to K values from 0 to 1.
Return the length of the longest (contiguous) subarray that contains only 1s.
Example 1:
Input: A = [1,1,1,0,0,0,1,1,1,1,0], K = 2
Output: 6
Explanation:
[1,1,1,0,0,1,1,1,1,1,1]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
Example 2:
Input: A = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], K = 3
Output: 10
Explanation:
[0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
Note:
1 <= A.length <= 20000
0 <= K <= A.length
A[i] is 0 or 1
|
class Solution:
def longestOnes(self, A: List[int], K: int) -> int:
ans , i , c = 0 , 0 , [ ]
for j in range( len( A ) ) :
if A[ j ] == 0 :
c += j ,
while len( c ) > K :
i = c.pop( 0 ) + 1
ans = max( ans , j - i + 1 )
return ans
#Sanyam Rajpal
|
Given an array A of 0s and 1s, we may change up to K values from 0 to 1.
Return the length of the longest (contiguous) subarray that contains only 1s.
Example 1:
Input: A = [1,1,1,0,0,0,1,1,1,1,0], K = 2
Output: 6
Explanation:
[1,1,1,0,0,1,1,1,1,1,1]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
Example 2:
Input: A = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], K = 3
Output: 10
Explanation:
[0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
Note:
1 <= A.length <= 20000
0 <= K <= A.length
A[i] is 0 or 1
|
class Solution:
def longestOnes(self, A: List[int], k: int) -> int:
res = 0
i = j = 0
move = 1
while i<len(A) and j<len(A):
if move==1:
if A[j]==0:
if k == 0:
move = 0
print(i,j)
res = max(res,j-i)
k -= 1
j += 1
if move==0:
if A[i]==0:
k += 1
move = 1
i += 1
return max(res,j-i)
|
Given an array A of 0s and 1s, we may change up to K values from 0 to 1.
Return the length of the longest (contiguous) subarray that contains only 1s.
Example 1:
Input: A = [1,1,1,0,0,0,1,1,1,1,0], K = 2
Output: 6
Explanation:
[1,1,1,0,0,1,1,1,1,1,1]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
Example 2:
Input: A = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], K = 3
Output: 10
Explanation:
[0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
Note:
1 <= A.length <= 20000
0 <= K <= A.length
A[i] is 0 or 1
|
class Solution:
def longestOnes(self, A: List[int], K: int) -> int:
start, end = 0, 0
for end in range(len(A)):
if A[end] == 0:
K -= 1
if K < 0:
if A[start] == 0:
K += 1
start += 1
return end - start + 1
|
Given an array A of 0s and 1s, we may change up to K values from 0 to 1.
Return the length of the longest (contiguous) subarray that contains only 1s.
Example 1:
Input: A = [1,1,1,0,0,0,1,1,1,1,0], K = 2
Output: 6
Explanation:
[1,1,1,0,0,1,1,1,1,1,1]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
Example 2:
Input: A = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], K = 3
Output: 10
Explanation:
[0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
Note:
1 <= A.length <= 20000
0 <= K <= A.length
A[i] is 0 or 1
|
class Solution:
def longestOnes(self, A: List[int], K: int) -> int:
ans = 0
l = 0
r = 0
prefix = [0 for i in range(len(A))]
for i in range(len(A)):
if (i==0):
prefix[i] = A[0]
else:
prefix[i] = A[i] + prefix[i-1]
if (K>=len(A)-prefix[-1]):
return len(A)
while (r<len(A) and l<len(A)):
while (r<len(A)):
if (l==0):
this_sum = prefix[r]
else:
this_sum = prefix[r] - prefix[l-1]
if (r-l+1-this_sum>K):
r-=1
break
r+=1
if (r>=len(A)):
if (r-l>ans):
#print (l,r,ans)
ans = r-l
break
if (r-l+1>ans):
#print (l,r,ans)
ans = r-l+1
#r+=1
while (l<len(A) and A[l] == 1):
l+=1
l+=1
return ans
|
Given an array A of 0s and 1s, we may change up to K values from 0 to 1.
Return the length of the longest (contiguous) subarray that contains only 1s.
Example 1:
Input: A = [1,1,1,0,0,0,1,1,1,1,0], K = 2
Output: 6
Explanation:
[1,1,1,0,0,1,1,1,1,1,1]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
Example 2:
Input: A = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], K = 3
Output: 10
Explanation:
[0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
Note:
1 <= A.length <= 20000
0 <= K <= A.length
A[i] is 0 or 1
|
class Solution:
def longestOnes(self, A: List[int], K: int) -> int:
count=0
maxCount=-1
first=0
for i in range(len(A)):
if A[i]==0 and K!=0:
count+=1
K-=1
elif A[i]==0 and K==0:
while A[first]!=0:
first+=1
count-=1
first+=1
else:
count+=1
maxCount=max(maxCount,count)
return maxCount
|
Given an array A of 0s and 1s, we may change up to K values from 0 to 1.
Return the length of the longest (contiguous) subarray that contains only 1s.
Example 1:
Input: A = [1,1,1,0,0,0,1,1,1,1,0], K = 2
Output: 6
Explanation:
[1,1,1,0,0,1,1,1,1,1,1]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
Example 2:
Input: A = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], K = 3
Output: 10
Explanation:
[0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
Note:
1 <= A.length <= 20000
0 <= K <= A.length
A[i] is 0 or 1
|
class Solution:
def longestOnes(self, A: List[int], K: int) -> int:
# don't reduce window - time O(n); space O(1)
left = 0
for right in range(len(A)):
K -= (1 - A[right])
if K < 0:
K += (1 - A[left])
left += 1
return right - left + 1
|
Given an array A of 0s and 1s, we may change up to K values from 0 to 1.
Return the length of the longest (contiguous) subarray that contains only 1s.
Example 1:
Input: A = [1,1,1,0,0,0,1,1,1,1,0], K = 2
Output: 6
Explanation:
[1,1,1,0,0,1,1,1,1,1,1]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
Example 2:
Input: A = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], K = 3
Output: 10
Explanation:
[0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
Note:
1 <= A.length <= 20000
0 <= K <= A.length
A[i] is 0 or 1
|
class Solution:
def longestOnes(self, A: List[int], K: int) -> int:
i, j = 0, 0
count = 0
out = 0
for i in range(len(A)):
if A[i] == 0:
count += 1
while count > K and j < len(A):
if A[j] == 0:
count -= 1
j += 1
out = max(out, i - j + 1)
return out
|
Given an array A of 0s and 1s, we may change up to K values from 0 to 1.
Return the length of the longest (contiguous) subarray that contains only 1s.
Example 1:
Input: A = [1,1,1,0,0,0,1,1,1,1,0], K = 2
Output: 6
Explanation:
[1,1,1,0,0,1,1,1,1,1,1]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
Example 2:
Input: A = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], K = 3
Output: 10
Explanation:
[0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
Note:
1 <= A.length <= 20000
0 <= K <= A.length
A[i] is 0 or 1
|
class Solution:
def longestOnes(self, a: List[int], K: int) -> int:
i = 0
j = 0
ml = 0
while i < len(a):
if a[i] == 0:
K -= 1
while K < 0:
if a[j] == 0:
K += 1
j += 1
ml = max(ml, i-j+1)
i += 1
return ml
|
Given an array A of 0s and 1s, we may change up to K values from 0 to 1.
Return the length of the longest (contiguous) subarray that contains only 1s.
Example 1:
Input: A = [1,1,1,0,0,0,1,1,1,1,0], K = 2
Output: 6
Explanation:
[1,1,1,0,0,1,1,1,1,1,1]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
Example 2:
Input: A = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], K = 3
Output: 10
Explanation:
[0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
Note:
1 <= A.length <= 20000
0 <= K <= A.length
A[i] is 0 or 1
|
class Solution:
def longestOnes(self, A: List[int], K: int) -> int:
'''naive
sliding window
keep growing sliding window rhs as num of 0s in window is >k
when num 0s == k, slide lhs of window until k > num 0s again
keep track of largest sliding window'''
if not A:
return 0
best_window_len = 0
p, q = 0, 0
num_zeros = 0
#if A[q] == 0: num_zeros += 1
while q < len(A):
if A[q] == 0: num_zeros += 1
#print(p, q, q - p)
if num_zeros > K:
best_window_len = max(q - p, best_window_len)
#print(\"running best:\", best_window_len)
while num_zeros > K:
if A[p] == 0:
num_zeros -= 1
p += 1
q+=1
best_window_len = max(q - p, best_window_len)
#if p == 0:
#best_window_len+=1
#print(best_window_len)
return best_window_len
|
Given an array A of 0s and 1s, we may change up to K values from 0 to 1.
Return the length of the longest (contiguous) subarray that contains only 1s.
Example 1:
Input: A = [1,1,1,0,0,0,1,1,1,1,0], K = 2
Output: 6
Explanation:
[1,1,1,0,0,1,1,1,1,1,1]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
Example 2:
Input: A = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], K = 3
Output: 10
Explanation:
[0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
Note:
1 <= A.length <= 20000
0 <= K <= A.length
A[i] is 0 or 1
|
class Solution:
def longestOnes(self, A: List[int], K: int) -> int:
subarrays = []
start = -1
i = 0
while i < len(A):
if A[i] == 1:
if start == -1:
start = i
else:
if start != -1:
subarrays.append([start, i])
start = -1
i += 1
if A[i-1] == 1:
subarrays.append([start, i])
print(subarrays)
if K == 0:
result = 0
for arr in subarrays:
if arr[1] - arr[0] > result:
result = arr[1] - arr[0]
return result
window = []
start = []
end = []
result = 0
for i in range(len(A)):
if A[i] == 0:
if len(window) == K:
window.pop(0)
window.append(i)
left = window[0] - 1
right = window[-1] + 1
while left >= 0 and A[left] != 0:
left -=1
while right < len(A) and A[right] != 0:
right += 1
if right - left > result:
result = right - left
# for i in range(start, len(subarrays)):
# if subarrays[i][0] > window[0]:
# break
# start = i
# for i in range(len(subarrays)-1, end-1, -1):
# if subarrays[i][1] < window[-1]:
# break
# end = i
# result = 0
# for curr_k in range(K, 0, -1)
# i = 0
# while i < len(subarrays) - 1:
# gap = subarrays[i][1] + subarrays[i][0] - 1
# if gap == curr_k:
return result - 1
|
Given an array A of 0s and 1s, we may change up to K values from 0 to 1.
Return the length of the longest (contiguous) subarray that contains only 1s.
Example 1:
Input: A = [1,1,1,0,0,0,1,1,1,1,0], K = 2
Output: 6
Explanation:
[1,1,1,0,0,1,1,1,1,1,1]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
Example 2:
Input: A = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], K = 3
Output: 10
Explanation:
[0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
Note:
1 <= A.length <= 20000
0 <= K <= A.length
A[i] is 0 or 1
|
class Solution:
def longestOnes(self, A: List[int], K: int) -> int:
start = end = 0
res = 0
map = collections.defaultdict(int)
while end < len(A):
map[A[end]] += 1
while end - start + 1 - map[1] > K:
map[A[start]] -= 1
start += 1
res = max(res, end-start+1)
end += 1
return res
|
Given an array A of 0s and 1s, we may change up to K values from 0 to 1.
Return the length of the longest (contiguous) subarray that contains only 1s.
Example 1:
Input: A = [1,1,1,0,0,0,1,1,1,1,0], K = 2
Output: 6
Explanation:
[1,1,1,0,0,1,1,1,1,1,1]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
Example 2:
Input: A = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], K = 3
Output: 10
Explanation:
[0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
Note:
1 <= A.length <= 20000
0 <= K <= A.length
A[i] is 0 or 1
|
class Solution:
def longestOnes(self, A: List[int], K: int) -> int:
begins = [-1] * (K+1)
cur = [0] * (K+1)
maxL = 0
curMax = 0
for i, a in enumerate(A):
if a == 0:
maxL = max(maxL, curMax)
begins.pop(0)
begins.append(i)
curMax -= cur.pop(0)
curMax += 1 if begins[0] == -1 else 0
cur.append(0)
else:
cur[-1] += 1
curMax += 1
return max(maxL, curMax)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.