inputs
stringlengths 50
14k
| targets
stringlengths 4
655k
|
|---|---|
Strings A and B are K-similar (for some non-negative integer K) if we can swap the positions of two letters in A exactly K times so that the resulting string equals B.
Given two anagrams A and B, return the smallest K for which A and B are K-similar.
Example 1:
Input: A = "ab", B = "ba"
Output: 1
Example 2:
Input: A = "abc", B = "bca"
Output: 2
Example 3:
Input: A = "abac", B = "baca"
Output: 2
Example 4:
Input: A = "aabc", B = "abca"
Output: 2
Note:
1 <= A.length == B.length <= 20
A and B contain only lowercase letters from the set {'a', 'b', 'c', 'd', 'e', 'f'}
|
class Solution:
# save the indices of letters that are in the right place
# create array 'correct' where the index corresponds to the letter in A and the value is the correct index
# find every letter pair --> a pair is two letters in B that when swapped, will end up in the correct index
# dynamic programming? number of displaced letters --> min # of swaps
# subproblem = number of displaced letters
# at most 20 swaps
def kSimilarity(self, A: str, B: str) -> int:
q, visited = [(A,0)], {A}
# BFS
for x, dist in q:
if x == B: return dist
for y in self.generate_neighbour_strings(x, B):
if y not in visited:
visited.add(y), q.append((y,dist+1))
def generate_neighbour_strings(self, x, B):
i = 0
while x[i] == B[i]: i+=1
for j in range(i+1, len(x)):
if x[j] == B[i] and x[j] != B[j]: yield x[:i]+x[j]+x[i+1:j]+x[i]+x[j+1:]
|
Strings A and B are K-similar (for some non-negative integer K) if we can swap the positions of two letters in A exactly K times so that the resulting string equals B.
Given two anagrams A and B, return the smallest K for which A and B are K-similar.
Example 1:
Input: A = "ab", B = "ba"
Output: 1
Example 2:
Input: A = "abc", B = "bca"
Output: 2
Example 3:
Input: A = "abac", B = "baca"
Output: 2
Example 4:
Input: A = "aabc", B = "abca"
Output: 2
Note:
1 <= A.length == B.length <= 20
A and B contain only lowercase letters from the set {'a', 'b', 'c', 'd', 'e', 'f'}
|
class Solution:
def kSimilarity(self, A: str, B: str) -> int:
if A == B:
return 0
queue = collections.deque([A])
visited = set([A])
step = 0
while queue:
for _ in range(len(queue)):
curr = queue.popleft()
for nxt in self.findNext(curr, B):
if nxt == B:
return step + 1
if nxt in visited:
continue
queue.append(nxt)
visited.add(nxt)
step += 1
return -1
def findNext(self, curr, B):
for i in range(len(curr)):
if curr[i] != B[i]:
break
for j in range(i + 1, len(B)):
if curr[j] == B[i]:
yield curr[:i] + curr[j] + curr[i + 1: j] + curr[i] + curr[j + 1:]
|
Strings A and B are K-similar (for some non-negative integer K) if we can swap the positions of two letters in A exactly K times so that the resulting string equals B.
Given two anagrams A and B, return the smallest K for which A and B are K-similar.
Example 1:
Input: A = "ab", B = "ba"
Output: 1
Example 2:
Input: A = "abc", B = "bca"
Output: 2
Example 3:
Input: A = "abac", B = "baca"
Output: 2
Example 4:
Input: A = "aabc", B = "abca"
Output: 2
Note:
1 <= A.length == B.length <= 20
A and B contain only lowercase letters from the set {'a', 'b', 'c', 'd', 'e', 'f'}
|
class Solution:
def kSimilarity(self, A: str, B: str) -> int:
return self.recursion(A, B, {})
def recursion(self, A: str, B: str, memo: dict) -> int:
if A == '':
return 0
key = A + ',' + B
if key in memo:
return memo[key]
if A[0] == B[0]:
return self.recursion(A[1:], B[1:], memo)
move = 100000
for i in range(1, len(A)):
if B[i] == A[0]:
tempB = B[1:i] + B[0] + B[i + 1:]
move = min(move, self.recursion(A[1:], tempB, memo))
memo[key] = move + 1
return 1 + move
|
Strings A and B are K-similar (for some non-negative integer K) if we can swap the positions of two letters in A exactly K times so that the resulting string equals B.
Given two anagrams A and B, return the smallest K for which A and B are K-similar.
Example 1:
Input: A = "ab", B = "ba"
Output: 1
Example 2:
Input: A = "abc", B = "bca"
Output: 2
Example 3:
Input: A = "abac", B = "baca"
Output: 2
Example 4:
Input: A = "aabc", B = "abca"
Output: 2
Note:
1 <= A.length == B.length <= 20
A and B contain only lowercase letters from the set {'a', 'b', 'c', 'd', 'e', 'f'}
|
class Solution:
from collections import deque
def kSimilarity(self, A: str, B: str) -> int:
if A==B: return 0
def G(pat):
for i in range(len(B)-1):
if pat[i] != B[i]:
break
ans = []
for j in range(i+1,len(B)):
if pat[j] == B[i]:
ans.append(pat[:i] + pat[j] + pat[i+1:j] + pat[i] + pat[j+1:])
return ans
Q = deque([])
visited = set()
visited.add(A)
Q.append((0,A))
while(Q):
lv, pat = Q.popleft()
#if pat==B:
# return lv
for new in G(pat):
if new not in visited:
visited.add(new)
Q.append((lv+1,new))
if new == B:
return lv+1
#print(Q,visited)
|
Strings A and B are K-similar (for some non-negative integer K) if we can swap the positions of two letters in A exactly K times so that the resulting string equals B.
Given two anagrams A and B, return the smallest K for which A and B are K-similar.
Example 1:
Input: A = "ab", B = "ba"
Output: 1
Example 2:
Input: A = "abc", B = "bca"
Output: 2
Example 3:
Input: A = "abac", B = "baca"
Output: 2
Example 4:
Input: A = "aabc", B = "abca"
Output: 2
Note:
1 <= A.length == B.length <= 20
A and B contain only lowercase letters from the set {'a', 'b', 'c', 'd', 'e', 'f'}
|
class Solution:
def kSimilarity(self, A: str, B: str) -> int:
if A==B: return 0
N = len(A)
dq = deque([(A, 0)])
cnt = 0
seen = {A}
while dq:
length = len(dq)
for _ in range(length):
a, idx = dq.popleft()
for i in range(idx, N):
if a[i]!=B[i]:
break
else:
return cnt
lst = list(a)
for j in range(i+1, N):
if a[j]!=B[j] and a[j]==B[i]:
lst[j], lst[i] = lst[i], lst[j]
state = ''.join(lst)
if state not in seen:
seen.add(state)
dq.append((state, i+1))
lst[j], lst[i] = lst[i], lst[j]
if a[i]==B[j]:
break
cnt += 1
|
Strings A and B are K-similar (for some non-negative integer K) if we can swap the positions of two letters in A exactly K times so that the resulting string equals B.
Given two anagrams A and B, return the smallest K for which A and B are K-similar.
Example 1:
Input: A = "ab", B = "ba"
Output: 1
Example 2:
Input: A = "abc", B = "bca"
Output: 2
Example 3:
Input: A = "abac", B = "baca"
Output: 2
Example 4:
Input: A = "aabc", B = "abca"
Output: 2
Note:
1 <= A.length == B.length <= 20
A and B contain only lowercase letters from the set {'a', 'b', 'c', 'd', 'e', 'f'}
|
class Solution:
def kSimilarity(self, A: str, B: str) -> int:
def get_neis(s):
res = []
for i in range(N):
if s[i]!=B[i]:
break
temp = list(s)
for j in range(i+1, N):
if s[j]==B[i]: #and s[j]!=B[j]:
temp[i], temp[j] = temp[j], temp[i]
res.append(''.join(temp))
temp[i], temp[j] = temp[j], temp[i]
return res
if A==B: return 0
N = len(A)
dq = deque([A])
seen = set([A])
cnt = 0
while dq:
length = len(dq)
for _ in range(length):
s = dq.popleft()
for nei in get_neis(s):
if nei==B: return cnt+1
if nei not in seen:
seen.add(nei)
dq.append(nei)
cnt += 1
|
Strings A and B are K-similar (for some non-negative integer K) if we can swap the positions of two letters in A exactly K times so that the resulting string equals B.
Given two anagrams A and B, return the smallest K for which A and B are K-similar.
Example 1:
Input: A = "ab", B = "ba"
Output: 1
Example 2:
Input: A = "abc", B = "bca"
Output: 2
Example 3:
Input: A = "abac", B = "baca"
Output: 2
Example 4:
Input: A = "aabc", B = "abca"
Output: 2
Note:
1 <= A.length == B.length <= 20
A and B contain only lowercase letters from the set {'a', 'b', 'c', 'd', 'e', 'f'}
|
class Solution:
@lru_cache(None)
def kSimilarity(self, A: str, B: str) -> int:
if len(A) == 0: return 0
if A[0]==B[0]: return self.kSimilarity(A[1:],B[1:])
ans = math.inf
for i in range(1,len(B)):
if B[i]==A[0]: ans = min(ans, 1+self.kSimilarity(A[1:],B[1:i]+B[0]+B[i+1:]))
return ans
|
Strings A and B are K-similar (for some non-negative integer K) if we can swap the positions of two letters in A exactly K times so that the resulting string equals B.
Given two anagrams A and B, return the smallest K for which A and B are K-similar.
Example 1:
Input: A = "ab", B = "ba"
Output: 1
Example 2:
Input: A = "abc", B = "bca"
Output: 2
Example 3:
Input: A = "abac", B = "baca"
Output: 2
Example 4:
Input: A = "aabc", B = "abca"
Output: 2
Note:
1 <= A.length == B.length <= 20
A and B contain only lowercase letters from the set {'a', 'b', 'c', 'd', 'e', 'f'}
|
class Solution:
def kSimilarity(self, A: str, B: str) -> int:
if A==B:
return 0
step_list = []
A_list = []
for i in range(len(A)):
A_list.append(A[i])
states = [[A_list.copy(),0,0],] #list, index, step
while states != []:
state = states.pop(0)
indictor = 0
for i in range(state[1],len(A_list)):
if state[0][i] != B[i]:
indictor = 1
for j in range(i+1,len(A_list)):
if state[0][j] == B[i] and B[j] != state[0][j]:
new_state = state[0].copy()
new_state[j], new_state[i] = new_state[i], new_state[j]
states.append([new_state,i+1,state[2]+1])
if B[j] == state[0][i]:
break
break
if indictor == 0:
step_list.append(state[2])
return min(step_list)
|
Strings A and B are K-similar (for some non-negative integer K) if we can swap the positions of two letters in A exactly K times so that the resulting string equals B.
Given two anagrams A and B, return the smallest K for which A and B are K-similar.
Example 1:
Input: A = "ab", B = "ba"
Output: 1
Example 2:
Input: A = "abc", B = "bca"
Output: 2
Example 3:
Input: A = "abac", B = "baca"
Output: 2
Example 4:
Input: A = "aabc", B = "abca"
Output: 2
Note:
1 <= A.length == B.length <= 20
A and B contain only lowercase letters from the set {'a', 'b', 'c', 'd', 'e', 'f'}
|
class Solution:
def kSimilarity2(self, A, B):
def nei(x):
i = 0
while x[i] == B[i]:
i+=1
for j in range(i+1, len(x)):
if x[j] == B[i] and x[i] != x[j]:
yield x[:i]+x[j]+x[i+1:j]+x[i]+x[j+1:]
q, seen = collections.deque([(A,0)]), {A}
while q:
x, d = q.popleft()
if x == B:
return d
for y in nei(x):
if y not in seen:
seen.add(y), q.append((y,d+1))
def kSimilarity(self, A: str, B: str) -> int:
if A == B:
return 0
m = len(A)
def getNeighbors(word):
i = 0
while word[i] == B[i]:
i+=1
for j in range(i+1, m):
if word[j] == B[i] and word[j] != word[i]:
yield word[:i] + word[j] + word[i+1:j] + word[i] + word[j+1:]
visited = {A}
queue = collections.deque([(A, 0)])
while queue:
word, d = queue.popleft()
if word == B:
return d
for nbor in getNeighbors(word):
if nbor not in visited:
visited.add(nbor)
queue.append((nbor, d+1))
|
Strings A and B are K-similar (for some non-negative integer K) if we can swap the positions of two letters in A exactly K times so that the resulting string equals B.
Given two anagrams A and B, return the smallest K for which A and B are K-similar.
Example 1:
Input: A = "ab", B = "ba"
Output: 1
Example 2:
Input: A = "abc", B = "bca"
Output: 2
Example 3:
Input: A = "abac", B = "baca"
Output: 2
Example 4:
Input: A = "aabc", B = "abca"
Output: 2
Note:
1 <= A.length == B.length <= 20
A and B contain only lowercase letters from the set {'a', 'b', 'c', 'd', 'e', 'f'}
|
class Solution:
@lru_cache(None)
def kSimilarity(self, A: str, B: str) -> int:
if len(A) == 0: return 0
if A[0]==B[0]: return self.kSimilarity(A[1:],B[1:])
ans = math.inf
for i in range(1,len(B)):
if B[i]==A[0]: ans = min(ans, 1+self.kSimilarity(A[1:],B[1:i]+B[0]+B[i+1:]))
return ans
|
Strings A and B are K-similar (for some non-negative integer K) if we can swap the positions of two letters in A exactly K times so that the resulting string equals B.
Given two anagrams A and B, return the smallest K for which A and B are K-similar.
Example 1:
Input: A = "ab", B = "ba"
Output: 1
Example 2:
Input: A = "abc", B = "bca"
Output: 2
Example 3:
Input: A = "abac", B = "baca"
Output: 2
Example 4:
Input: A = "aabc", B = "abca"
Output: 2
Note:
1 <= A.length == B.length <= 20
A and B contain only lowercase letters from the set {'a', 'b', 'c', 'd', 'e', 'f'}
|
class Solution:
def kSimilarity(self, A, B):
# def nei(x):
# i = 0
# while x[i] == B[i]: i += 1
# for j in range(i + 1, len(A)):
# if x[j] == B[j]:
# continue
# if x[j] == B[i] and x[i] == B[j]:
# yield x[:i] + x[j] + x[i + 1:j] + x[i] + x[j + 1:]
# break
# if x[j] == B[i]:
# yield x[:i] + x[j] + x[i + 1:j] + x[i] + x[j + 1:]
# # def test():
# stack = [(A, 0)]
# visit = {A}
# while stack:
# cur, d = stack.pop()
# if cur == B: return d
# for neighbor in nei(cur):
# if neighbor not in visit:
# visit.add(neighbor)
# stack.append((neighbor, d+1))
n = len(A)
def nei(x):
i = 0
while x[i] == B[i]: i += 1
for j in range(i+1,n):
if x[j] == B[j]:
continue
if x[j] == B[i] and x[i] == B[j]:
yield x[:i]+x[j]+x[i+1:j]+x[i]+x[j+1:]
break
if x[j] == B[i]:
yield x[:i]+x[j]+x[i+1:j]+x[i]+x[j+1:]
pool = [(A,0)]
seen = {A}
for x,d in pool:
if x == B: return d
for y in nei(x):
if y not in seen:
seen.add(y)
pool.append((y,d+1))
|
Strings A and B are K-similar (for some non-negative integer K) if we can swap the positions of two letters in A exactly K times so that the resulting string equals B.
Given two anagrams A and B, return the smallest K for which A and B are K-similar.
Example 1:
Input: A = "ab", B = "ba"
Output: 1
Example 2:
Input: A = "abc", B = "bca"
Output: 2
Example 3:
Input: A = "abac", B = "baca"
Output: 2
Example 4:
Input: A = "aabc", B = "abca"
Output: 2
Note:
1 <= A.length == B.length <= 20
A and B contain only lowercase letters from the set {'a', 'b', 'c', 'd', 'e', 'f'}
|
class Solution:
def kSimilarity(self, A: str, B: str) -> int:
mem = dict()
def process(A,B):
key = '%s_%s'%(A,B)
if A==B:
return 0
if key in mem:
return mem[key]
if A[0] == B[0]:
return process(A[1:],B[1:])
c2 = float('inf')
temp = list(B)
for idx,val in enumerate(B):
if val == A[0]:
temp[idx],temp[0] = temp[0],temp[idx]
c2 = min(c2,1+process(A[1:],''.join(temp)[1:]))
temp[0],temp[idx] = temp[idx],temp[0]
mem[key]=c2
return mem[key]
return process(A,B)
|
Strings A and B are K-similar (for some non-negative integer K) if we can swap the positions of two letters in A exactly K times so that the resulting string equals B.
Given two anagrams A and B, return the smallest K for which A and B are K-similar.
Example 1:
Input: A = "ab", B = "ba"
Output: 1
Example 2:
Input: A = "abc", B = "bca"
Output: 2
Example 3:
Input: A = "abac", B = "baca"
Output: 2
Example 4:
Input: A = "aabc", B = "abca"
Output: 2
Note:
1 <= A.length == B.length <= 20
A and B contain only lowercase letters from the set {'a', 'b', 'c', 'd', 'e', 'f'}
|
from functools import lru_cache
class Solution:
def kSimilarity(self, A: str, B: str) -> int:
@lru_cache(None)
def solve(s1, s2):
if not s1:
return 0
if s1[0] == s2[0]:
return solve(s1[1:], s2[1:])
ans = 21
for i,c in enumerate(s1):
if s2[0] == c:
ans = min(ans, 1 + solve(s1[1:i] + s1[0] + s1[i+1:], s2[1:]))
return ans
return solve(A, B)
|
Strings A and B are K-similar (for some non-negative integer K) if we can swap the positions of two letters in A exactly K times so that the resulting string equals B.
Given two anagrams A and B, return the smallest K for which A and B are K-similar.
Example 1:
Input: A = "ab", B = "ba"
Output: 1
Example 2:
Input: A = "abc", B = "bca"
Output: 2
Example 3:
Input: A = "abac", B = "baca"
Output: 2
Example 4:
Input: A = "aabc", B = "abca"
Output: 2
Note:
1 <= A.length == B.length <= 20
A and B contain only lowercase letters from the set {'a', 'b', 'c', 'd', 'e', 'f'}
|
class Solution:
def kSimilarity(self, A: str, B: str) -> int:
q = collections.deque()
visited = set()
q.append(A)
visited.add(A)
step = -1
while q:
step += 1
lens = len(q)
for _ in range(lens):
curr = q.popleft()
if curr == B:
return step
#print(self._swap(curr, B))
for next in self._swap(curr, B):
if next in visited:
continue
q.append(next)
visited.add(next)
def _swap(self, s, B):
i = 0
while s[i] == B[i]:
i += 1
if s[i]!=B[i]:
for j in range(i + 1, len(s)):
if s[j] == B[i]:
yield s[:i] + s[j] + s[i+1:j] + s[i] + s[j+1:]
|
Strings A and B are K-similar (for some non-negative integer K) if we can swap the positions of two letters in A exactly K times so that the resulting string equals B.
Given two anagrams A and B, return the smallest K for which A and B are K-similar.
Example 1:
Input: A = "ab", B = "ba"
Output: 1
Example 2:
Input: A = "abc", B = "bca"
Output: 2
Example 3:
Input: A = "abac", B = "baca"
Output: 2
Example 4:
Input: A = "aabc", B = "abca"
Output: 2
Note:
1 <= A.length == B.length <= 20
A and B contain only lowercase letters from the set {'a', 'b', 'c', 'd', 'e', 'f'}
|
class Solution:
def kSimilarity(self, A, B):
def nei(x):
i = 0
while x[i] == B[i]:
i+=1
for j in range(i+1, len(x)):
if x[j] == B[i] and x[i] != x[j]:
yield x[:i]+x[j]+x[i+1:j]+x[i]+x[j+1:]
q, seen = collections.deque([(A,0)]), {A}
while q:
x, d = q.popleft()
print(x)
if x == B:
return d
for y in nei(x):
if y not in seen:
seen.add(y), q.append((y,d+1))
|
Strings A and B are K-similar (for some non-negative integer K) if we can swap the positions of two letters in A exactly K times so that the resulting string equals B.
Given two anagrams A and B, return the smallest K for which A and B are K-similar.
Example 1:
Input: A = "ab", B = "ba"
Output: 1
Example 2:
Input: A = "abc", B = "bca"
Output: 2
Example 3:
Input: A = "abac", B = "baca"
Output: 2
Example 4:
Input: A = "aabc", B = "abca"
Output: 2
Note:
1 <= A.length == B.length <= 20
A and B contain only lowercase letters from the set {'a', 'b', 'c', 'd', 'e', 'f'}
|
class Solution:
def kSimilarity(self, A: str, B: str) -> int:
if A==B:
return 0
step_list = []
A_list = []
for i in range(len(A)):
A_list.append(A[i])
states = [[A_list.copy(),0,0],] #list, index, step
while states != []:
state = states.pop(0)
indictor = 0
for i in range(state[1],len(A_list)):
if state[0][i] != B[i]:
indictor = 1
for j in range(i+1,len(A_list)):
if state[0][j] == B[i] and B[j] != state[0][j] and B[j] == state[0][i]:
new_state = state[0].copy()
new_state[j], new_state[i] = new_state[i], new_state[j]
states.append([new_state,i+1,state[2]+1])
break
elif state[0][j] == B[i] and B[j] != state[0][j]:
new_state = state[0].copy()
new_state[j], new_state[i] = new_state[i], new_state[j]
states.append([new_state,i+1,state[2]+1])
break
if indictor == 0:
step_list.append(state[2])
return min(step_list)
|
Strings A and B are K-similar (for some non-negative integer K) if we can swap the positions of two letters in A exactly K times so that the resulting string equals B.
Given two anagrams A and B, return the smallest K for which A and B are K-similar.
Example 1:
Input: A = "ab", B = "ba"
Output: 1
Example 2:
Input: A = "abc", B = "bca"
Output: 2
Example 3:
Input: A = "abac", B = "baca"
Output: 2
Example 4:
Input: A = "aabc", B = "abca"
Output: 2
Note:
1 <= A.length == B.length <= 20
A and B contain only lowercase letters from the set {'a', 'b', 'c', 'd', 'e', 'f'}
|
class Solution:
def kSimilarity(self, A: str, B: str) -> int:
dic = {c: i for i, c in enumerate('abcdef')}
bag = dict()
stack = []
for a, b in zip(A, B):
if a != b:
i, j = dic[a], dic[b]
bag[(i, j)] = bag.get((i, j), 0) + 1
stack.append((i, j))
output = 0
# @lru_cache(maxsize=None)
def search(stack):
if not stack:
return 0
i, j = stack.pop()
if (j, i) in stack:
idx = stack.index((j, i))
stack = stack[:idx] + stack[(idx + 1):]
return search(stack) + 1
else:
best = float(inf)
for idx, pair in enumerate(stack):
if pair[0] == j:
curr = search(stack[:idx] + [(i, pair[1])] + stack[(idx + 1):]) + 1
best = min(curr, best)
return best
return search(stack)
|
Strings A and B are K-similar (for some non-negative integer K) if we can swap the positions of two letters in A exactly K times so that the resulting string equals B.
Given two anagrams A and B, return the smallest K for which A and B are K-similar.
Example 1:
Input: A = "ab", B = "ba"
Output: 1
Example 2:
Input: A = "abc", B = "bca"
Output: 2
Example 3:
Input: A = "abac", B = "baca"
Output: 2
Example 4:
Input: A = "aabc", B = "abca"
Output: 2
Note:
1 <= A.length == B.length <= 20
A and B contain only lowercase letters from the set {'a', 'b', 'c', 'd', 'e', 'f'}
|
class Solution:
def kSimilarity(self, A: str, B: str) -> int:
n = len(A)
A = list(A)
B = list(B)
base = 0
for i in range(n):
if A[i] == B[i]: continue
for j in range(i+1, n):
if A[i] == B[j] and A[j] == B[i]:
A[i], A[j] = A[j], A[i]
base += 1
break
# invariant: A[:i] == B[:i]
def dfs(i):
if i == n: return 0
if A[i] == B[i]:
return dfs(i+1)
desired = B[i]
cand = float('inf')
for j in range(i+1, n):
if A[j] == desired:
A[i], A[j] = A[j], A[i]
cand = min(cand, 1 + dfs(i+1))
A[i], A[j] = A[j], A[i]
return cand
return base + dfs(0)
|
Strings A and B are K-similar (for some non-negative integer K) if we can swap the positions of two letters in A exactly K times so that the resulting string equals B.
Given two anagrams A and B, return the smallest K for which A and B are K-similar.
Example 1:
Input: A = "ab", B = "ba"
Output: 1
Example 2:
Input: A = "abc", B = "bca"
Output: 2
Example 3:
Input: A = "abac", B = "baca"
Output: 2
Example 4:
Input: A = "aabc", B = "abca"
Output: 2
Note:
1 <= A.length == B.length <= 20
A and B contain only lowercase letters from the set {'a', 'b', 'c', 'd', 'e', 'f'}
|
from collections import deque
class Solution:
def kSimilarity(self, A: str, B: str) -> int:
## check official solution and
## https://leetcode.com/problems/k-similar-strings/discuss/269517/Python-Graph-BFS
q = deque()
q.append(A)
visited = set([A])
res = 0
def neighbors(x):
res = []
i = 0
while i<len(x) and x[i] == B[i]:
i += 1
for j in range(i+1, len(A)):
if x[j] == B[i]:
new_str = x[:i] + x[j] + x[i+1:j] + x[i] + x[j+1:]
if new_str not in visited:
visited.add(new_str)
res.append(new_str)
return res
while len(q)>0:
q_sz = len(q)
for _ in range(q_sz):
cur = q.popleft()
if cur == B:
return res
for neighbor in neighbors(cur):
q.append(neighbor)
res += 1
return res
|
Strings A and B are K-similar (for some non-negative integer K) if we can swap the positions of two letters in A exactly K times so that the resulting string equals B.
Given two anagrams A and B, return the smallest K for which A and B are K-similar.
Example 1:
Input: A = "ab", B = "ba"
Output: 1
Example 2:
Input: A = "abc", B = "bca"
Output: 2
Example 3:
Input: A = "abac", B = "baca"
Output: 2
Example 4:
Input: A = "aabc", B = "abca"
Output: 2
Note:
1 <= A.length == B.length <= 20
A and B contain only lowercase letters from the set {'a', 'b', 'c', 'd', 'e', 'f'}
|
class Solution:
def kSimilarity(self, A: str, B: str) -> int:
queue = collections.deque([(A, 0, 0)])
s = {A}
while queue:
curr_A, curr_k, curr_p = queue.popleft()
# print(curr_A, curr_k, curr_p)
if curr_A == B:
return curr_k
for i in range(curr_p, len(A)):
if curr_A[i] != B[i]:
for j in range(i+1, len(A)):
if curr_A[j] == B[i] and curr_A[:i] + curr_A[j] + curr_A[i+1: j] + curr_A[i] + curr_A[j+1:] not in s:
queue.append((curr_A[:i] + curr_A[j] + curr_A[i+1: j] + curr_A[i] + curr_A[j+1:], curr_k + 1, i + 1))
s.add(curr_A[:i] + curr_A[j] + curr_A[i+1: j] + curr_A[i] + curr_A[j+1:])
break
|
Strings A and B are K-similar (for some non-negative integer K) if we can swap the positions of two letters in A exactly K times so that the resulting string equals B.
Given two anagrams A and B, return the smallest K for which A and B are K-similar.
Example 1:
Input: A = "ab", B = "ba"
Output: 1
Example 2:
Input: A = "abc", B = "bca"
Output: 2
Example 3:
Input: A = "abac", B = "baca"
Output: 2
Example 4:
Input: A = "aabc", B = "abca"
Output: 2
Note:
1 <= A.length == B.length <= 20
A and B contain only lowercase letters from the set {'a', 'b', 'c', 'd', 'e', 'f'}
|
class Solution:
def kSimilarity(self, A: str, B: str) -> int:
queue = collections.deque([(A, 0, 0)])
s = {A}
while queue:
curr_A, curr_k, curr_p = queue.popleft()
if curr_A == B:
return curr_k
for i in range(curr_p, len(A)):
if curr_A[i] != B[i]:
for j in range(i+1, len(A)):
if curr_A[j] == B[i] and curr_A[:i] + curr_A[j] + curr_A[i+1: j] + curr_A[i] + curr_A[j+1:] not in s:
queue.append((curr_A[:i] + curr_A[j] + curr_A[i+1: j] + curr_A[i] + curr_A[j+1:], curr_k + 1, i + 1))
s.add(curr_A[:i] + curr_A[j] + curr_A[i+1: j] + curr_A[i] + curr_A[j+1:])
break
|
Strings A and B are K-similar (for some non-negative integer K) if we can swap the positions of two letters in A exactly K times so that the resulting string equals B.
Given two anagrams A and B, return the smallest K for which A and B are K-similar.
Example 1:
Input: A = "ab", B = "ba"
Output: 1
Example 2:
Input: A = "abc", B = "bca"
Output: 2
Example 3:
Input: A = "abac", B = "baca"
Output: 2
Example 4:
Input: A = "aabc", B = "abca"
Output: 2
Note:
1 <= A.length == B.length <= 20
A and B contain only lowercase letters from the set {'a', 'b', 'c', 'd', 'e', 'f'}
|
class Solution:
def kSimilarity(self, A: str, B: str) -> int:
queue = []
queue.append((A,B,0))
step = len(A)
minFlip = float('inf')
seen = {(A,B):0}
while(queue):
target, current, flip = queue.pop(0)
if seen[(target,current)] < flip:
continue
if target == current:
minFlip = min(minFlip,flip)
continue
if target[0] == current[0]:
temp = seen.get((target[1:], current[1:]), None)
if not temp:
seen[(target[1:], current[1:])] = flip
else:
if temp <= flip:
continue
seen[(target[1:], current[1:])] = flip
queue.append((target[1:], current[1:], flip))
else:
canni = [idx for idx, char in enumerate(current) if char == target[0]]
piror = canni
#piror = [(loc, target[loc] == current[0]) for loc in canni]
#piror.sort(key=lambda x:x[1],reverse = True)
for loc in piror:
lol = (target[1:], current[1:loc] + current[0] + current[loc+1:])
temp = seen.get(lol, None)
if not temp:
seen[lol] = flip+1
else:
if temp <= flip+1:
continue
seen[lol] = flip + 1
queue.append((target[1:], current[1:loc] + current[0] + current[loc+1:], flip + 1))
return minFlip
|
Strings A and B are K-similar (for some non-negative integer K) if we can swap the positions of two letters in A exactly K times so that the resulting string equals B.
Given two anagrams A and B, return the smallest K for which A and B are K-similar.
Example 1:
Input: A = "ab", B = "ba"
Output: 1
Example 2:
Input: A = "abc", B = "bca"
Output: 2
Example 3:
Input: A = "abac", B = "baca"
Output: 2
Example 4:
Input: A = "aabc", B = "abca"
Output: 2
Note:
1 <= A.length == B.length <= 20
A and B contain only lowercase letters from the set {'a', 'b', 'c', 'd', 'e', 'f'}
|
class Solution:
def kSimilarity(self, A: str, B: str) -> int:
def dist(a, b):
# count number of differing characters
return sum( (1 if c!=d else 0 for (c,d) in zip(a,b) ) )
def swap(s, i, j):
# swap ith and jth chars of string s
# assert i != j
if i > j:
i, j = j, i
return s[:i] + s[j] + s[i+1:j] + s[i] + s[j+1:]
def DFS(string, k):
# can string be swapped into problem's str `A` in `k` moves?
if string == A:
return True
if k == 0:
return False
# early break if distance is too great:
# best possible for string of length N:
# N is even: N/2 (every swap corrects 2 letters
# N is odd: N//2 + 1
# every swap until last 3 letters corrects 2
# last 3 letters take 2 swaps
distance = dist(string, A)
best = distance/2 if distance % 2 == 0 else (distance//2) + 1
if k < best:
return False
for i,c in enumerate(string):
if A[i] == c:
continue
# c is wrong, we need to swap a correct letter into it
# only look for after current position to avoid double swaps
for j in range(i, len(A)):
if string[j] == A[i] and A[j] != A[i]:
# try this swap
if DFS(swap(string, i, j), k-1):
return True
# return False after trying the first wrong letter (because of trick):
# if there is any `k` solution, then there's a `k` solution
# that starts on this letter
return False
for k in range(len(A)):
if DFS(B, k):
return k
|
Strings A and B are K-similar (for some non-negative integer K) if we can swap the positions of two letters in A exactly K times so that the resulting string equals B.
Given two anagrams A and B, return the smallest K for which A and B are K-similar.
Example 1:
Input: A = "ab", B = "ba"
Output: 1
Example 2:
Input: A = "abc", B = "bca"
Output: 2
Example 3:
Input: A = "abac", B = "baca"
Output: 2
Example 4:
Input: A = "aabc", B = "abca"
Output: 2
Note:
1 <= A.length == B.length <= 20
A and B contain only lowercase letters from the set {'a', 'b', 'c', 'd', 'e', 'f'}
|
class Solution:
def kSimilarity(self, A: str, B: str) -> int:
q = collections.deque()
visited = set()
q.append(A)
visited.add(A)
level = 0
def getNext(S, B):
S = list(S)
res = []
i = 0
while i < len(S):
if S[i] != B[i]:
break
i += 1
for j in range(i + 1, len(S)):
if S[j] == B[i]:
S[j], S[i] = S[i], S[j]
res.append(''.join(S))
S[j], S[i] = S[i], S[j]
return res
while q:
for _ in range(len(q)):
curr = q.popleft()
if curr == B:
return level
for next_str in getNext(curr, B):
if next_str not in visited:
q.append(next_str)
visited.add(next_str)
level += 1
return -1
|
Strings A and B are K-similar (for some non-negative integer K) if we can swap the positions of two letters in A exactly K times so that the resulting string equals B.
Given two anagrams A and B, return the smallest K for which A and B are K-similar.
Example 1:
Input: A = "ab", B = "ba"
Output: 1
Example 2:
Input: A = "abc", B = "bca"
Output: 2
Example 3:
Input: A = "abac", B = "baca"
Output: 2
Example 4:
Input: A = "aabc", B = "abca"
Output: 2
Note:
1 <= A.length == B.length <= 20
A and B contain only lowercase letters from the set {'a', 'b', 'c', 'd', 'e', 'f'}
|
class Solution:
def kSimilarity(self, A: str, B: str) -> int:
def mk_similarities(s): # len(s) == len(B)
for i, c in enumerate(B):
if s[i] != c:
break
res = []
for j in range(i + 1, len(B)):
if s[j] == B[i]:
ns = list(s)
ns[i], ns[j] = ns[j], ns[i]
res.append(''.join(ns))
return res
N = len(A)
ws = [A]
swaps = 0
seen = {A}
while ws:
nws = []
for _ in range(len(ws)):
s = ws.pop(0)
# print(s)
if s == B:
return swaps
similarities = mk_similarities(s)
# print(similarities)
for similarity in similarities:
if similarity not in seen:
nws.append(similarity)
seen.add(similarity)
ws = nws
swaps += 1
return None
# swaps = 0
# N = len(A)
# A = list(A)
# for i, c in enumerate(B):
# if A[i] == c:
# pass
# else:
# nearest_c = None
# for j in range(i + 1, N):
# if A[j] == c:
# nearest_c = j
# break
# if nearest_c is None:
# return None
# else:
# A[i], A[j] = A[j], A[i]
# swaps += 1
# return swaps
|
Strings A and B are K-similar (for some non-negative integer K) if we can swap the positions of two letters in A exactly K times so that the resulting string equals B.
Given two anagrams A and B, return the smallest K for which A and B are K-similar.
Example 1:
Input: A = "ab", B = "ba"
Output: 1
Example 2:
Input: A = "abc", B = "bca"
Output: 2
Example 3:
Input: A = "abac", B = "baca"
Output: 2
Example 4:
Input: A = "aabc", B = "abca"
Output: 2
Note:
1 <= A.length == B.length <= 20
A and B contain only lowercase letters from the set {'a', 'b', 'c', 'd', 'e', 'f'}
|
class Solution:
def kSimilarity(self, A: str, B: str) -> int:
def getSwap(S): # 用于获取一个节点下可以扩展的所有节点
for i, c in enumerate(S): # 找到第一个不相等的字符的-位置-
if c != B[i]: break
T = list(S)
for j in range(i + 1, len(S)): # 获取所有的可扩展的子节点
if S[j] == B[i]: # 找到就交换
T[i], T[j] = T[j], T[i]
yield ''.join(T) # 返回一个节点
T[j], T[i] = T[i], T[j] # 恢复当前环境,以便寻找下一个可扩展的节点
queue, cnt = [A], {A: 0} # 初始化队列,cnt用于记录当前结点已经走了多少步
while queue:
S = queue[0] # 出队
del queue[0]
if S == B: return cnt[S] # 结束
for T in getSwap(S): # 获取当前节点所有扩展子节点
if T not in cnt: # 如果没有出现过,则入队
cnt[T] = cnt[S] + 1
queue.append(T)
|
Strings A and B are K-similar (for some non-negative integer K) if we can swap the positions of two letters in A exactly K times so that the resulting string equals B.
Given two anagrams A and B, return the smallest K for which A and B are K-similar.
Example 1:
Input: A = "ab", B = "ba"
Output: 1
Example 2:
Input: A = "abc", B = "bca"
Output: 2
Example 3:
Input: A = "abac", B = "baca"
Output: 2
Example 4:
Input: A = "aabc", B = "abca"
Output: 2
Note:
1 <= A.length == B.length <= 20
A and B contain only lowercase letters from the set {'a', 'b', 'c', 'd', 'e', 'f'}
|
class Solution:
def kSimilarity(self, A: str, B: str) -> int:
def mk_similarities(s): # len(s) == len(B)
for i, c in enumerate(B):
if s[i] != c:
break
res = []
for j in range(i + 1, len(B)):
if s[j] == B[i]:
ns = list(s)
ns[i], ns[j] = ns[j], ns[i]
res.append(''.join(ns))
return res
N = len(A)
ws = [A]
swaps = 0
seen = {A}
while ws:
nws = []
for _ in range(len(ws)):
s = ws.pop(0)
# print(s)
if s == B:
return swaps
similarities = mk_similarities(s)
# print(similarities)
for similarity in similarities:
if similarity not in seen:
nws.append(similarity)
seen.add(similarity)
ws = nws
swaps += 1
return None
|
Strings A and B are K-similar (for some non-negative integer K) if we can swap the positions of two letters in A exactly K times so that the resulting string equals B.
Given two anagrams A and B, return the smallest K for which A and B are K-similar.
Example 1:
Input: A = "ab", B = "ba"
Output: 1
Example 2:
Input: A = "abc", B = "bca"
Output: 2
Example 3:
Input: A = "abac", B = "baca"
Output: 2
Example 4:
Input: A = "aabc", B = "abca"
Output: 2
Note:
1 <= A.length == B.length <= 20
A and B contain only lowercase letters from the set {'a', 'b', 'c', 'd', 'e', 'f'}
|
class Solution:
def kSimilarity(self, A: str, B: str) -> int:
@lru_cache(None)
def nei(x):
i = 0
while i < len(x) and x[i] == B[i]: i+=1
res = []
for j in range(i+1, len(x)):
if x[j] == B[i]:
res.append(x[:i]+x[j]+x[i+1:j]+x[i]+x[j+1:])
return res
q, seen = [(A,0)], {A}
for x, d in q:
if x == B: return d
for y in nei(x):
if y not in seen:
seen.add(y), q.append((y,d+1))
|
Strings A and B are K-similar (for some non-negative integer K) if we can swap the positions of two letters in A exactly K times so that the resulting string equals B.
Given two anagrams A and B, return the smallest K for which A and B are K-similar.
Example 1:
Input: A = "ab", B = "ba"
Output: 1
Example 2:
Input: A = "abc", B = "bca"
Output: 2
Example 3:
Input: A = "abac", B = "baca"
Output: 2
Example 4:
Input: A = "aabc", B = "abca"
Output: 2
Note:
1 <= A.length == B.length <= 20
A and B contain only lowercase letters from the set {'a', 'b', 'c', 'd', 'e', 'f'}
|
class Solution:
def kSimilarity(self, A, B):
def nei(x):
i = 0
while x[i] == B[i]: i+=1
for j in range(i+1, len(x)):
if x[j] == B[i]: yield x[:i]+x[j]+x[i+1:j]+x[i]+x[j+1:]
q, seen = [(A,0)], {A}
for x, d in q:
if x == B: return d
for y in nei(x):
if y not in seen:
seen.add(y), q.append((y,d+1))
|
Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied.
A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.
Example 1:
Input: nums = [10,2,-10,5,20], k = 2
Output: 37
Explanation: The subsequence is [10, 2, 5, 20].
Example 2:
Input: nums = [-1,-2,-3], k = 1
Output: -1
Explanation: The subsequence must be non-empty, so we choose the largest number.
Example 3:
Input: nums = [10,-2,-10,-5,20], k = 2
Output: 23
Explanation: The subsequence is [10, -2, -5, 20].
Constraints:
1 <= k <= nums.length <= 10^5
-10^4 <= nums[i] <= 10^4
|
from collections import deque
class Solution:
def constrainedSubsetSum(self, nums, k):
N, queue = len(nums), deque()
dp = [val for val in nums]
for i, val in enumerate(nums):
if queue and (i - queue[0] > k):
queue.popleft()
if queue and dp[queue[0]] > 0:
dp[i] += dp[queue[0]]
while queue and dp[i] >= dp[queue[-1]]:
queue.pop()
queue.append(i)
return max(dp)
|
Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied.
A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.
Example 1:
Input: nums = [10,2,-10,5,20], k = 2
Output: 37
Explanation: The subsequence is [10, 2, 5, 20].
Example 2:
Input: nums = [-1,-2,-3], k = 1
Output: -1
Explanation: The subsequence must be non-empty, so we choose the largest number.
Example 3:
Input: nums = [10,-2,-10,-5,20], k = 2
Output: 23
Explanation: The subsequence is [10, -2, -5, 20].
Constraints:
1 <= k <= nums.length <= 10^5
-10^4 <= nums[i] <= 10^4
|
from collections import deque
class Solution:
def constrainedSubsetSum(self, nums: List[int], k: int) -> int:
dp = nums.copy()
ans = dp[0]
monoq = deque()
qsize = 0
for i, num in enumerate(nums):
if i > 0:
dp[i] = max(dp[i], num + monoq[0][0])
ans = max(ans, dp[i])
pops = 1
while monoq and dp[i] > monoq[-1][0]:
_, freq = monoq.pop()
pops += freq
qsize -= freq
monoq.append([dp[i], pops])
qsize += pops
while qsize > k:
extra = qsize - k
if monoq[0][1] > extra:
monoq[0][1] -= extra
qsize = k
else:
_, v = monoq.popleft()
qsize -= v
return ans
|
Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied.
A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.
Example 1:
Input: nums = [10,2,-10,5,20], k = 2
Output: 37
Explanation: The subsequence is [10, 2, 5, 20].
Example 2:
Input: nums = [-1,-2,-3], k = 1
Output: -1
Explanation: The subsequence must be non-empty, so we choose the largest number.
Example 3:
Input: nums = [10,-2,-10,-5,20], k = 2
Output: 23
Explanation: The subsequence is [10, -2, -5, 20].
Constraints:
1 <= k <= nums.length <= 10^5
-10^4 <= nums[i] <= 10^4
|
from collections import deque
class Solution:
def constrainedSubsetSum(self, nums: List[int], k: int) -> int:
dp = []
dp.append(nums[0])
deq = deque()
deq.append(0)
for i in range(1, len(nums)):
while len(deq) and (i - deq[0]) > k:
deq.popleft()
cur_max = dp[deq[0]] if len(deq) and dp[deq[0]] > 0 else 0
dp.append(cur_max + nums[i])
while len(deq) and dp[deq[-1]] < dp[i]:
deq.pop()
deq.append(i)
return max(dp)
|
Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied.
A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.
Example 1:
Input: nums = [10,2,-10,5,20], k = 2
Output: 37
Explanation: The subsequence is [10, 2, 5, 20].
Example 2:
Input: nums = [-1,-2,-3], k = 1
Output: -1
Explanation: The subsequence must be non-empty, so we choose the largest number.
Example 3:
Input: nums = [10,-2,-10,-5,20], k = 2
Output: 23
Explanation: The subsequence is [10, -2, -5, 20].
Constraints:
1 <= k <= nums.length <= 10^5
-10^4 <= nums[i] <= 10^4
|
from heapq import heappop
from heapq import heappush
class Solution:
def constrainedSubsetSum(self, nums: List[int], k: int) -> int:
# -val, val, idx
heap = []
ans = -10001
for i, num in enumerate(nums):
while len(heap) > 0:
_, val, idx = heap[0]
if idx < i - k: # out of constraint
heappop(heap)
else:
new_val = max(num, val + num)
ans = max(ans, new_val)
heappush(heap, (-new_val, new_val, i))
break
if len(heap) == 0: # no valid previous item
ans = max(ans, num)
heappush(heap, (-num, num, i))
return ans
|
Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied.
A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.
Example 1:
Input: nums = [10,2,-10,5,20], k = 2
Output: 37
Explanation: The subsequence is [10, 2, 5, 20].
Example 2:
Input: nums = [-1,-2,-3], k = 1
Output: -1
Explanation: The subsequence must be non-empty, so we choose the largest number.
Example 3:
Input: nums = [10,-2,-10,-5,20], k = 2
Output: 23
Explanation: The subsequence is [10, -2, -5, 20].
Constraints:
1 <= k <= nums.length <= 10^5
-10^4 <= nums[i] <= 10^4
|
class Solution:
def constrainedSubsetSum(self, nums: List[int], k: int) -> int:
n=len(nums)
dp=[-sys.maxsize]*n
dq=[]
dp[n-1]=nums[n-1]
res=dp[n-1]
for i in range(n-2,-1,-1):
while(len(dq)!=0 and dp[i+1]>dp[dq[-1]]):
dq.pop()
while(len(dq)!=0 and dq[0]>i+k):
dq.pop(0)
dq.append(i+1)
dp[i]=max(dp[i],nums[i],nums[i]+dp[dq[0]])
res=max(res,dp[i])
return res
|
Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied.
A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.
Example 1:
Input: nums = [10,2,-10,5,20], k = 2
Output: 37
Explanation: The subsequence is [10, 2, 5, 20].
Example 2:
Input: nums = [-1,-2,-3], k = 1
Output: -1
Explanation: The subsequence must be non-empty, so we choose the largest number.
Example 3:
Input: nums = [10,-2,-10,-5,20], k = 2
Output: 23
Explanation: The subsequence is [10, -2, -5, 20].
Constraints:
1 <= k <= nums.length <= 10^5
-10^4 <= nums[i] <= 10^4
|
class Solution:
def constrainedSubsetSum(self, nums: List[int], k: int) -> int:
withAdding = [0 for _ in range(len(nums))]
notAdding = [-1 for _ in range(len(nums))]
validMax = [nums[0]]
maxValue = nums[0]
withAdding[0] = nums[0]
for i in range(1, len(nums)):
if maxValue < 0 and nums[i] > maxValue:
withAdding[i] = nums[i]
else:
withAdding[i] = maxValue + nums[i]
validMax.append(withAdding[i])
maxValue = max(withAdding[i], maxValue)
if len(validMax) > k and validMax.pop(0) == maxValue:
maxValue = max(validMax)
notAdding[i] = max(notAdding[i - 1], withAdding[i - 1])
return max(max(notAdding), max(withAdding))
|
Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied.
A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.
Example 1:
Input: nums = [10,2,-10,5,20], k = 2
Output: 37
Explanation: The subsequence is [10, 2, 5, 20].
Example 2:
Input: nums = [-1,-2,-3], k = 1
Output: -1
Explanation: The subsequence must be non-empty, so we choose the largest number.
Example 3:
Input: nums = [10,-2,-10,-5,20], k = 2
Output: 23
Explanation: The subsequence is [10, -2, -5, 20].
Constraints:
1 <= k <= nums.length <= 10^5
-10^4 <= nums[i] <= 10^4
|
class Solution:
def constrainedSubsetSum(self, nums: List[int], k: int) -> int:
memo=[nums[0]]
if not nums:
return 0
m=nums[0]
for i in range(1,k):
memo.append(nums[i]+max(0,m))
if memo[-1]>m:
m=memo[-1]
import copy
window=copy.deepcopy(memo)
#m=max(window)
for i in range(k,len(nums)):
#print(m,memo,window)
memo.append(nums[i]+max(0,m))
window.append(memo[-1])
p=window.pop(0)
if memo[-1]>m:
m=memo[-1]
elif p==m:
m=max(window)
return max(memo)
|
Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied.
A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.
Example 1:
Input: nums = [10,2,-10,5,20], k = 2
Output: 37
Explanation: The subsequence is [10, 2, 5, 20].
Example 2:
Input: nums = [-1,-2,-3], k = 1
Output: -1
Explanation: The subsequence must be non-empty, so we choose the largest number.
Example 3:
Input: nums = [10,-2,-10,-5,20], k = 2
Output: 23
Explanation: The subsequence is [10, -2, -5, 20].
Constraints:
1 <= k <= nums.length <= 10^5
-10^4 <= nums[i] <= 10^4
|
from collections import deque
class Solution:
def constrainedSubsetSum(self, nums, k):
N, queue = len(nums), deque()
dp = [0] * N
for i, val in enumerate(nums):
if queue and (i - queue[0] > k):
#if i > k and (queue[0] == i - k - 1):
queue.popleft()
#dp[i] = (val + max(dp[queue[0]], 0)) if queue else val
if queue and dp[queue[0]] > 0:
dp[i] = val + dp[queue[0]]
else:
dp[i] = val
while queue and dp[i] >= dp[queue[-1]]:
queue.pop()
queue.append(i)
return max(dp)
from collections import deque
class Solution:
def constrainedSubsetSum(self, nums, k):
if not nums or not k: return 0
if max(nums) <= 0: return max(nums)
if min(nums) >= 0: return sum(nums)
queue, N = deque(), len(nums)
for i in range(N):
#if queue and (i - queue[0] > k):
while queue and queue[0] < i - k:
queue.popleft()
# compute the max sum we can get at index i
if queue:
nums[i] += nums[queue[0]]
# delet all the sequence that smaller than current sum, becaus there will never be
# considers ==> smaller than current sequence, and end before current sequence
while queue and nums[queue[-1]] < nums[i]:
queue.pop()
# if nums[i] < 0, it can't be a useful prefix sum
if nums[i] > 0:
queue.append(i)
return max(nums)
|
Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied.
A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.
Example 1:
Input: nums = [10,2,-10,5,20], k = 2
Output: 37
Explanation: The subsequence is [10, 2, 5, 20].
Example 2:
Input: nums = [-1,-2,-3], k = 1
Output: -1
Explanation: The subsequence must be non-empty, so we choose the largest number.
Example 3:
Input: nums = [10,-2,-10,-5,20], k = 2
Output: 23
Explanation: The subsequence is [10, -2, -5, 20].
Constraints:
1 <= k <= nums.length <= 10^5
-10^4 <= nums[i] <= 10^4
|
from collections import deque
class Solution:
def constrainedSubsetSum(self, nums, k):
if max(nums) <= 0: return max(nums) # optimization
if min(nums) >= 0: return sum(nums) # optimization
N, queue = len(nums), deque()
dp = [val for val in nums]
for i, val in enumerate(nums):
if queue and (i - queue[0] > k):
queue.popleft()
if queue and dp[queue[0]] > 0:
dp[i] += dp[queue[0]]
while queue and dp[i] >= dp[queue[-1]]:
queue.pop()
queue.append(i)
return max(dp)
|
Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied.
A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.
Example 1:
Input: nums = [10,2,-10,5,20], k = 2
Output: 37
Explanation: The subsequence is [10, 2, 5, 20].
Example 2:
Input: nums = [-1,-2,-3], k = 1
Output: -1
Explanation: The subsequence must be non-empty, so we choose the largest number.
Example 3:
Input: nums = [10,-2,-10,-5,20], k = 2
Output: 23
Explanation: The subsequence is [10, -2, -5, 20].
Constraints:
1 <= k <= nums.length <= 10^5
-10^4 <= nums[i] <= 10^4
|
class Solution:
def constrainedSubsetSum(self, nums: List[int], k: int) -> int:
dp=[nums[0]]
decrease=collections.deque([0])
for i,num in enumerate(nums[1:],1):
if decrease and i-decrease[0]>k:
decrease.popleft()
val=max(num,dp[decrease[0]]+num)
dp.append(val)
while decrease and dp[decrease[-1]]<=val:
decrease.pop()
decrease.append(i)
return max(dp)
|
Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied.
A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.
Example 1:
Input: nums = [10,2,-10,5,20], k = 2
Output: 37
Explanation: The subsequence is [10, 2, 5, 20].
Example 2:
Input: nums = [-1,-2,-3], k = 1
Output: -1
Explanation: The subsequence must be non-empty, so we choose the largest number.
Example 3:
Input: nums = [10,-2,-10,-5,20], k = 2
Output: 23
Explanation: The subsequence is [10, -2, -5, 20].
Constraints:
1 <= k <= nums.length <= 10^5
-10^4 <= nums[i] <= 10^4
|
from collections import deque
class Solution:
def constrainedSubsetSum(self, nums, k):
if max(nums) <= 0: return max(nums) # optimization
if min(nums) >= 0: return sum(nums) # optimization
N, queue = len(nums), deque()
dp = [val for val in nums]
for i, val in enumerate(nums):
if queue and (i - queue[0] > k):
queue.popleft()
if queue and dp[queue[0]] > 0:
dp[i] += dp[queue[0]]
while queue and dp[i] >= dp[queue[-1]]:
queue.pop()
queue.append(i)
return dp[queue[0]]
|
Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied.
A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.
Example 1:
Input: nums = [10,2,-10,5,20], k = 2
Output: 37
Explanation: The subsequence is [10, 2, 5, 20].
Example 2:
Input: nums = [-1,-2,-3], k = 1
Output: -1
Explanation: The subsequence must be non-empty, so we choose the largest number.
Example 3:
Input: nums = [10,-2,-10,-5,20], k = 2
Output: 23
Explanation: The subsequence is [10, -2, -5, 20].
Constraints:
1 <= k <= nums.length <= 10^5
-10^4 <= nums[i] <= 10^4
|
class Solution:
def constrainedSubsetSum(self, nums: List[int], k: int) -> int:
n = len(nums)
_max = collections.deque()
res = max(nums)
for i in range(n):
if len(_max) and _max[0][0] > 0:
val = nums[i] + _max[0][0]
else:
val = nums[i]
while len(_max) and _max[-1][0] < val: _max.pop()
_max.append((val, i))
res = max(val, res)
if _max[0][1] <= i-k:
_max.popleft()
return res
|
Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied.
A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.
Example 1:
Input: nums = [10,2,-10,5,20], k = 2
Output: 37
Explanation: The subsequence is [10, 2, 5, 20].
Example 2:
Input: nums = [-1,-2,-3], k = 1
Output: -1
Explanation: The subsequence must be non-empty, so we choose the largest number.
Example 3:
Input: nums = [10,-2,-10,-5,20], k = 2
Output: 23
Explanation: The subsequence is [10, -2, -5, 20].
Constraints:
1 <= k <= nums.length <= 10^5
-10^4 <= nums[i] <= 10^4
|
class Solution:
def constrainedSubsetSum(self, nums: List[int], k: int) -> int:
maxNum = nums[0]
maxSum = nums[0]
maxNegSum = 0
curNegWindowSum = 0
curWindowSum = 0
rightIndex = 0
leftIndex = 0
midIndex = 0
negativeStreak = False
while rightIndex < len(nums):
if maxNum < nums[rightIndex]:
maxNum = nums[rightIndex]
if nums[rightIndex] >= 0 and not negativeStreak:
curWindowSum += nums[rightIndex]
maxSum = max(maxSum, curWindowSum)
elif nums[rightIndex] < 0 and not negativeStreak:
negativeStreak = True
midIndex = rightIndex
if k > 1:
curNegWindowSum = nums[rightIndex]
maxNegSum = curNegWindowSum
curWindowSum += nums[rightIndex]
elif nums[rightIndex] < 0 and negativeStreak:
if rightIndex - midIndex < k - 1:
curNegWindowSum += nums[rightIndex]
maxNegSum = curNegWindowSum
else:
if k > 1:
curNegWindowSum -= nums[midIndex]
curNegWindowSum += nums[rightIndex]
maxNegSum = min(maxNegSum, curNegWindowSum)
midIndex += 1
curWindowSum += nums[rightIndex]
elif nums[rightIndex] >= 0 and negativeStreak:
curWindowSum -= maxNegSum
if curWindowSum <= 0:
midIndex = rightIndex
leftIndex = rightIndex
curWindowSum = nums[rightIndex]
else:
curWindowSum += nums[rightIndex]
maxSum = max(maxSum, curWindowSum)
maxNegSum = 0
curNegWindowSum = 0
negativeStreak = False
rightIndex += 1
return max(maxSum, maxNum)
|
Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied.
A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.
Example 1:
Input: nums = [10,2,-10,5,20], k = 2
Output: 37
Explanation: The subsequence is [10, 2, 5, 20].
Example 2:
Input: nums = [-1,-2,-3], k = 1
Output: -1
Explanation: The subsequence must be non-empty, so we choose the largest number.
Example 3:
Input: nums = [10,-2,-10,-5,20], k = 2
Output: 23
Explanation: The subsequence is [10, -2, -5, 20].
Constraints:
1 <= k <= nums.length <= 10^5
-10^4 <= nums[i] <= 10^4
|
class Solution:
def constrainedSubsetSum(self, nums: List[int], k: int) -> int:
dp = [nums[0]]
decrease = collections.deque([0])
for i, x in enumerate(nums[1:], 1):
if decrease[0] == i-k-1:
decrease.popleft()
tmp = max(x, dp[decrease[0]] + x)
dp += [tmp]
while decrease and dp[decrease[-1]] <= tmp:
decrease.pop()
decrease += [i]
return max(dp)
|
Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied.
A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.
Example 1:
Input: nums = [10,2,-10,5,20], k = 2
Output: 37
Explanation: The subsequence is [10, 2, 5, 20].
Example 2:
Input: nums = [-1,-2,-3], k = 1
Output: -1
Explanation: The subsequence must be non-empty, so we choose the largest number.
Example 3:
Input: nums = [10,-2,-10,-5,20], k = 2
Output: 23
Explanation: The subsequence is [10, -2, -5, 20].
Constraints:
1 <= k <= nums.length <= 10^5
-10^4 <= nums[i] <= 10^4
|
class Solution:
def constrainedSubsetSum(self, A: List[int], k: int) -> int:
deque = collections.deque()
for i in range(len(A)):
A[i] += deque[0] if deque else 0
while len(deque) and A[i] > deque[-1]:
deque.pop()
if A[i] > 0:
deque.append(A[i])
if i >= k and deque and deque[0] == A[i-k]:
deque.popleft()
return max(A)
|
Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied.
A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.
Example 1:
Input: nums = [10,2,-10,5,20], k = 2
Output: 37
Explanation: The subsequence is [10, 2, 5, 20].
Example 2:
Input: nums = [-1,-2,-3], k = 1
Output: -1
Explanation: The subsequence must be non-empty, so we choose the largest number.
Example 3:
Input: nums = [10,-2,-10,-5,20], k = 2
Output: 23
Explanation: The subsequence is [10, -2, -5, 20].
Constraints:
1 <= k <= nums.length <= 10^5
-10^4 <= nums[i] <= 10^4
|
class Solution:
def constrainedSubsetSum(self, nums: List[int], k: int) -> int:
q_max, ans = deque([(nums[0],0)]), nums[0]
for i in range(1,len(nums)):
nums[i] += max(q_max[0][0],0)
if q_max[0][1] <= i-k:
q_max.popleft()
while q_max and nums[i] > q_max[-1][0]:
q_max.pop()
q_max.append((nums[i],i))
ans = max(ans, nums[i])
return ans
|
Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied.
A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.
Example 1:
Input: nums = [10,2,-10,5,20], k = 2
Output: 37
Explanation: The subsequence is [10, 2, 5, 20].
Example 2:
Input: nums = [-1,-2,-3], k = 1
Output: -1
Explanation: The subsequence must be non-empty, so we choose the largest number.
Example 3:
Input: nums = [10,-2,-10,-5,20], k = 2
Output: 23
Explanation: The subsequence is [10, -2, -5, 20].
Constraints:
1 <= k <= nums.length <= 10^5
-10^4 <= nums[i] <= 10^4
|
class Solution:
def constrainedSubsetSum(self, nums: List[int], k: int) -> int:
dq=collections.deque()
m=-sys.maxsize
for i,n in enumerate(nums):
fi = n
if dq:
fi += max(dq[0][1], 0)
while dq and fi>=dq[-1][1]:
dq.pop()
dq.append([i,fi])
if i-dq[0][0]==k:
dq.popleft()
if fi>m:
m=fi
return m
|
Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied.
A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.
Example 1:
Input: nums = [10,2,-10,5,20], k = 2
Output: 37
Explanation: The subsequence is [10, 2, 5, 20].
Example 2:
Input: nums = [-1,-2,-3], k = 1
Output: -1
Explanation: The subsequence must be non-empty, so we choose the largest number.
Example 3:
Input: nums = [10,-2,-10,-5,20], k = 2
Output: 23
Explanation: The subsequence is [10, -2, -5, 20].
Constraints:
1 <= k <= nums.length <= 10^5
-10^4 <= nums[i] <= 10^4
|
class Solution:
def constrainedSubsetSum(self, nums, k):
n = len(nums)
dp = [0] * n
deq = deque([0])
for i in range(n):
if deq and deq[0] < i - k:
deq.popleft()
while deq and nums[i] + dp[deq[0]] > dp[deq[-1]]:
a = deq.pop()
dp[i] = max(nums[i],nums[i] + dp[deq[0]] if deq else nums[i] + dp[a])
deq.append(i)
return max(dp)
|
Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied.
A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.
Example 1:
Input: nums = [10,2,-10,5,20], k = 2
Output: 37
Explanation: The subsequence is [10, 2, 5, 20].
Example 2:
Input: nums = [-1,-2,-3], k = 1
Output: -1
Explanation: The subsequence must be non-empty, so we choose the largest number.
Example 3:
Input: nums = [10,-2,-10,-5,20], k = 2
Output: 23
Explanation: The subsequence is [10, -2, -5, 20].
Constraints:
1 <= k <= nums.length <= 10^5
-10^4 <= nums[i] <= 10^4
|
class Solution:
def constrainedSubsetSum(self, nums: List[int], k: int) -> int:
q = deque([0])
ans = nums[0]
for i in range(1, len(nums)):
nums[i] += max(nums[q[0]], 0)
while q and nums[i] >= nums[q[-1]]:
q.pop()
q.append(i)
if i - q[0] == k:
q.popleft()
ans = max(ans, nums[i])
return ans
|
Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied.
A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.
Example 1:
Input: nums = [10,2,-10,5,20], k = 2
Output: 37
Explanation: The subsequence is [10, 2, 5, 20].
Example 2:
Input: nums = [-1,-2,-3], k = 1
Output: -1
Explanation: The subsequence must be non-empty, so we choose the largest number.
Example 3:
Input: nums = [10,-2,-10,-5,20], k = 2
Output: 23
Explanation: The subsequence is [10, -2, -5, 20].
Constraints:
1 <= k <= nums.length <= 10^5
-10^4 <= nums[i] <= 10^4
|
class Solution:
def constrainedSubsetSum(self, nums: List[int], k: int) -> int:
dp, q = [nums[0]], deque()
q.append((0,nums[0]))
res = nums[0]
for i in range(1, len(nums)):
while q and i - q[0][0] >k:
q.popleft()
cur = nums[i]
if q:
cur +=max(q[0][1],0)
while q and q[-1][1] < cur:
q.pop()
q.append((i,cur))
dp.append(cur)
res = max(res,cur)
return res
|
Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied.
A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.
Example 1:
Input: nums = [10,2,-10,5,20], k = 2
Output: 37
Explanation: The subsequence is [10, 2, 5, 20].
Example 2:
Input: nums = [-1,-2,-3], k = 1
Output: -1
Explanation: The subsequence must be non-empty, so we choose the largest number.
Example 3:
Input: nums = [10,-2,-10,-5,20], k = 2
Output: 23
Explanation: The subsequence is [10, -2, -5, 20].
Constraints:
1 <= k <= nums.length <= 10^5
-10^4 <= nums[i] <= 10^4
|
from collections import deque
class Solution:
def constrainedSubsetSum(self, A: List[int], k: int) -> int:
d = deque()
for i in range(len(A)):
A[i] += d[0] if d else 0
while d and d[-1] < A[i]:
d.pop()
if A[i] > 0:
d.append(A[i])
if i >= k and d and d[0] == A[i - k]:
d.popleft()
return max(A)
|
Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied.
A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.
Example 1:
Input: nums = [10,2,-10,5,20], k = 2
Output: 37
Explanation: The subsequence is [10, 2, 5, 20].
Example 2:
Input: nums = [-1,-2,-3], k = 1
Output: -1
Explanation: The subsequence must be non-empty, so we choose the largest number.
Example 3:
Input: nums = [10,-2,-10,-5,20], k = 2
Output: 23
Explanation: The subsequence is [10, -2, -5, 20].
Constraints:
1 <= k <= nums.length <= 10^5
-10^4 <= nums[i] <= 10^4
|
from collections import deque
'''
We need to figure out basically for k numbers remaining what is the largest sum, assuming that the first of those is selected.
'''
class Solution:
def constrainedSubsetSum(self, nums: List[int], k: int) -> int:
numLength = len(nums)
maxSums = defaultdict(int)
maxSum = nums[0]##as that is definitely a lower bound on the maxSum, as that is obviously a possible sum. Be careful when you initialize mins and maxs
maxQueue = deque([0])##this will be used to compute the list of values of the maxSum for the previousk indices.
for i in range(numLength-1,-1,-1):
ithMax = max(nums[i],maxQueue[0]+nums[i])##be careful of index name.
maxSums[i] = ithMax
##print(\"Max Queue before popping: \",maxQueue)
if len(maxQueue) == k:##be careful of variables
if maxSums[i+k] == maxQueue[0]:
maxQueue.popleft()##this is needed to ensure that we don't have values that have expired.
while maxQueue and ithMax > maxQueue[-1]:##be sure of spelling and using right variables
maxQueue.pop()
maxQueue.append(ithMax)
##print(\"Max Queue after popping: \",maxQueue)
maxSum = max(ithMax,maxSum)
return maxSum
|
Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied.
A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.
Example 1:
Input: nums = [10,2,-10,5,20], k = 2
Output: 37
Explanation: The subsequence is [10, 2, 5, 20].
Example 2:
Input: nums = [-1,-2,-3], k = 1
Output: -1
Explanation: The subsequence must be non-empty, so we choose the largest number.
Example 3:
Input: nums = [10,-2,-10,-5,20], k = 2
Output: 23
Explanation: The subsequence is [10, -2, -5, 20].
Constraints:
1 <= k <= nums.length <= 10^5
-10^4 <= nums[i] <= 10^4
|
class Solution:
def constrainedSubsetSum(self, nums: List[int], k: int) -> int:
dp = collections.deque([(nums[0], 0)])
ans = nums[0]
for i in range(1, len(nums)):
new = nums[i] + max(0,dp[0][0])
while dp and dp[0][1] <= i-k:
dp.popleft()
while dp and new >= dp[-1][0]:
dp.pop()
dp.append((new, i))
ans = max(ans, new)
return ans
|
Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied.
A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.
Example 1:
Input: nums = [10,2,-10,5,20], k = 2
Output: 37
Explanation: The subsequence is [10, 2, 5, 20].
Example 2:
Input: nums = [-1,-2,-3], k = 1
Output: -1
Explanation: The subsequence must be non-empty, so we choose the largest number.
Example 3:
Input: nums = [10,-2,-10,-5,20], k = 2
Output: 23
Explanation: The subsequence is [10, -2, -5, 20].
Constraints:
1 <= k <= nums.length <= 10^5
-10^4 <= nums[i] <= 10^4
|
from collections import deque
class Solution:
def constrainedSubsetSum(self, nums, k):
if max(nums) <= 0: return max(nums)
if min(nums) >= 0: return sum(nums)
queue, N = deque(), len(nums)
for i in range(N):
while queue and queue[0] < i - k:
queue.popleft()
if queue:
nums[i] += nums[queue[0]]
while queue and nums[queue[-1]] < nums[i]:
queue.pop()
if nums[i] > 0:
queue.append(i)
return max(nums)
|
Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied.
A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.
Example 1:
Input: nums = [10,2,-10,5,20], k = 2
Output: 37
Explanation: The subsequence is [10, 2, 5, 20].
Example 2:
Input: nums = [-1,-2,-3], k = 1
Output: -1
Explanation: The subsequence must be non-empty, so we choose the largest number.
Example 3:
Input: nums = [10,-2,-10,-5,20], k = 2
Output: 23
Explanation: The subsequence is [10, -2, -5, 20].
Constraints:
1 <= k <= nums.length <= 10^5
-10^4 <= nums[i] <= 10^4
|
class Solution:
def constrainedSubsetSum(self, nums: List[int], k: int) -> int:
n= len(nums)
dp = [0]*n
q = deque()
ans = float('-inf')
for i in range(n):
if i>k and q[0]==i-k-1:
q.popleft()
dp[i]= (0 if len(q)==0 else max(dp[q[0]],0)) + nums[i]
while len(q)>0 and dp[i]>=dp[q[-1]]:
q.pop()
q.append(i)
ans = max(ans, dp[i])
return ans
|
Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied.
A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.
Example 1:
Input: nums = [10,2,-10,5,20], k = 2
Output: 37
Explanation: The subsequence is [10, 2, 5, 20].
Example 2:
Input: nums = [-1,-2,-3], k = 1
Output: -1
Explanation: The subsequence must be non-empty, so we choose the largest number.
Example 3:
Input: nums = [10,-2,-10,-5,20], k = 2
Output: 23
Explanation: The subsequence is [10, -2, -5, 20].
Constraints:
1 <= k <= nums.length <= 10^5
-10^4 <= nums[i] <= 10^4
|
class Solution:
def constrainedSubsetSum(self, nums: List[int], k: int) -> int:
# dp[i] = nums[i] + max(dp[j] j - i <= k)
# max(dp)
n = len(nums)
from collections import deque
q = deque()
q.append((nums[-1], n-1))
ans = nums[-1]
for i in reversed(list(range(n-1))):
while q and q[0][1] - i > k:
q.popleft()
dp = nums[i]
if q:
dp = max(dp, nums[i] + q[0][0])
ans = max(dp, ans)
while q and q[-1][0] <= dp:
q.pop()
q.append((dp, i))
return ans
|
Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied.
A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.
Example 1:
Input: nums = [10,2,-10,5,20], k = 2
Output: 37
Explanation: The subsequence is [10, 2, 5, 20].
Example 2:
Input: nums = [-1,-2,-3], k = 1
Output: -1
Explanation: The subsequence must be non-empty, so we choose the largest number.
Example 3:
Input: nums = [10,-2,-10,-5,20], k = 2
Output: 23
Explanation: The subsequence is [10, -2, -5, 20].
Constraints:
1 <= k <= nums.length <= 10^5
-10^4 <= nums[i] <= 10^4
|
from collections import deque
class Solution:
def constrainedSubsetSum(self, nums: List[int], k: int) -> int:
n = len(nums)
queue = deque()
res = float('-inf')
for i in range(n):
if queue and i - queue[0][1] > k:
queue.popleft()
cur = nums[i] + max(0, (queue[0][0] if queue else 0))
res = max(res, cur)
while queue and queue[-1][0] <= cur:
queue.pop()
queue.append((cur, i))
return res
|
Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied.
A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.
Example 1:
Input: nums = [10,2,-10,5,20], k = 2
Output: 37
Explanation: The subsequence is [10, 2, 5, 20].
Example 2:
Input: nums = [-1,-2,-3], k = 1
Output: -1
Explanation: The subsequence must be non-empty, so we choose the largest number.
Example 3:
Input: nums = [10,-2,-10,-5,20], k = 2
Output: 23
Explanation: The subsequence is [10, -2, -5, 20].
Constraints:
1 <= k <= nums.length <= 10^5
-10^4 <= nums[i] <= 10^4
|
class Solution:
def constrainedSubsetSum(self, nums: List[int], k: int) -> int:
q = []
res = float('-inf')
for i in range(len(nums)):
while q and i-q[0][0] > k:
q.pop(0)
temp = nums[i]
if q and q[0][1] > 0:
temp += q[0][1]
res = max(res, temp)
while q and q[-1][1] <= temp:
q.pop()
q.append((i, temp))
return res
|
Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied.
A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.
Example 1:
Input: nums = [10,2,-10,5,20], k = 2
Output: 37
Explanation: The subsequence is [10, 2, 5, 20].
Example 2:
Input: nums = [-1,-2,-3], k = 1
Output: -1
Explanation: The subsequence must be non-empty, so we choose the largest number.
Example 3:
Input: nums = [10,-2,-10,-5,20], k = 2
Output: 23
Explanation: The subsequence is [10, -2, -5, 20].
Constraints:
1 <= k <= nums.length <= 10^5
-10^4 <= nums[i] <= 10^4
|
class Solution:
def constrainedSubsetSum(self, nums: List[int], k: int) -> int:
N = len(nums)
dp = [-math.inf] * N
q = deque() #. Val, Index
for i in range(N):
dp[i] = max(dp[i], nums[i] + (q[0][0] if q else 0), nums[i] )
while q and dp[i] > q[-1][0]:
q.pop()
while q and i - q[0][1] >= k:
q.popleft()
q.append((dp[i], i))
# print(dp)
return max(dp)
|
Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied.
A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.
Example 1:
Input: nums = [10,2,-10,5,20], k = 2
Output: 37
Explanation: The subsequence is [10, 2, 5, 20].
Example 2:
Input: nums = [-1,-2,-3], k = 1
Output: -1
Explanation: The subsequence must be non-empty, so we choose the largest number.
Example 3:
Input: nums = [10,-2,-10,-5,20], k = 2
Output: 23
Explanation: The subsequence is [10, -2, -5, 20].
Constraints:
1 <= k <= nums.length <= 10^5
-10^4 <= nums[i] <= 10^4
|
class Solution:
def constrainedSubsetSum(self, nums: List[int], k: int) -> int:
deq = deque()
for index, val in enumerate(nums):
nums[index] += deq[0] if deq else 0
while deq and nums[index]> deq[-1]:
deq.pop()
if nums[index]>0:
deq.append(nums[index])
if index>=k and deq and deq[0] == nums[index-k]:
deq.popleft()
return max(nums)
|
Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied.
A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.
Example 1:
Input: nums = [10,2,-10,5,20], k = 2
Output: 37
Explanation: The subsequence is [10, 2, 5, 20].
Example 2:
Input: nums = [-1,-2,-3], k = 1
Output: -1
Explanation: The subsequence must be non-empty, so we choose the largest number.
Example 3:
Input: nums = [10,-2,-10,-5,20], k = 2
Output: 23
Explanation: The subsequence is [10, -2, -5, 20].
Constraints:
1 <= k <= nums.length <= 10^5
-10^4 <= nums[i] <= 10^4
|
class Solution:
def constrainedSubsetSum(self, nums: List[int], k: int) -> int:
n = len(nums)
dp = [0] *n
dp[0] = nums[0]
heap = []
heappush(heap, (- nums[0], 0))
for i in range(1, n):
while heap[0][1] < i - k:
heappop(heap)
cur = heap[0][0]
dp[i] = nums[i] + max(- cur, 0)
heappush(heap, (- dp[i], i))
#print(dp)
return max(dp)
|
Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied.
A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.
Example 1:
Input: nums = [10,2,-10,5,20], k = 2
Output: 37
Explanation: The subsequence is [10, 2, 5, 20].
Example 2:
Input: nums = [-1,-2,-3], k = 1
Output: -1
Explanation: The subsequence must be non-empty, so we choose the largest number.
Example 3:
Input: nums = [10,-2,-10,-5,20], k = 2
Output: 23
Explanation: The subsequence is [10, -2, -5, 20].
Constraints:
1 <= k <= nums.length <= 10^5
-10^4 <= nums[i] <= 10^4
|
class Solution:
def constrainedSubsetSum(self, A, k):
deque = collections.deque()
for i in range(len(A)):
A[i] += deque[0] if deque else 0
while len(deque) and deque[-1] < A[i]:
deque.pop()
if A[i] > 0:
deque.append(A[i])
if i >= k and deque and deque[0] == A[i - k]:
deque.popleft()
return max(A)
|
Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied.
A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.
Example 1:
Input: nums = [10,2,-10,5,20], k = 2
Output: 37
Explanation: The subsequence is [10, 2, 5, 20].
Example 2:
Input: nums = [-1,-2,-3], k = 1
Output: -1
Explanation: The subsequence must be non-empty, so we choose the largest number.
Example 3:
Input: nums = [10,-2,-10,-5,20], k = 2
Output: 23
Explanation: The subsequence is [10, -2, -5, 20].
Constraints:
1 <= k <= nums.length <= 10^5
-10^4 <= nums[i] <= 10^4
|
class Solution:
def constrainedSubsetSum(self, nums: List[int], k: int) -> int:
n = len(nums)
dp = [-(math.inf) for i in range(n)]
dp[0] = nums[0]
ans = [nums[0]]
queue = [0]
for i in range(1,n):
dp[i] = max(dp[i], nums[i], nums[i]+ans[i-1])
if len(queue) == 0:
queue.append(i)
else:
while len(queue) > 0 and ((dp[i] > dp[queue[-1]]) or (i - queue[0]) >= k):
if dp[i] > dp[queue[-1]]:
queue.pop(-1)
else:
queue.pop(0)
queue.append(i)
ans.append(dp[queue[0]])
# print(ans)
# print(dp)
return (max(dp))
|
Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied.
A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.
Example 1:
Input: nums = [10,2,-10,5,20], k = 2
Output: 37
Explanation: The subsequence is [10, 2, 5, 20].
Example 2:
Input: nums = [-1,-2,-3], k = 1
Output: -1
Explanation: The subsequence must be non-empty, so we choose the largest number.
Example 3:
Input: nums = [10,-2,-10,-5,20], k = 2
Output: 23
Explanation: The subsequence is [10, -2, -5, 20].
Constraints:
1 <= k <= nums.length <= 10^5
-10^4 <= nums[i] <= 10^4
|
class Solution:
def constrainedSubsetSum(self, nums: List[int], k: int) -> int:
stack = deque()
for i in range(len(nums)):
nums[i] += stack[0] if stack else 0
while stack and stack[-1] < nums[i]:
stack.pop()
if i >= k and stack and stack[0] == nums[i-k]:
stack.popleft()
if nums[i] > 0:
stack.append(nums[i])
return max(nums)
q = deque()
for i in range(len(nums)):
nums[i] += q[0] if q else 0
while q and nums[i] > q[-1]:
q.pop()
if nums[i] > 0:
q.append(nums[i])
if i >= k and q and q[0] == nums[i-k]:
q.popleft()
return max(nums)
|
Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied.
A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.
Example 1:
Input: nums = [10,2,-10,5,20], k = 2
Output: 37
Explanation: The subsequence is [10, 2, 5, 20].
Example 2:
Input: nums = [-1,-2,-3], k = 1
Output: -1
Explanation: The subsequence must be non-empty, so we choose the largest number.
Example 3:
Input: nums = [10,-2,-10,-5,20], k = 2
Output: 23
Explanation: The subsequence is [10, -2, -5, 20].
Constraints:
1 <= k <= nums.length <= 10^5
-10^4 <= nums[i] <= 10^4
|
class Solution:
def constrainedSubsetSum(self, nums: List[int], k: int) -> int:
#用来保留k步内的累加最大值
deque = collections.deque()
for i in range(len(nums)):
if deque:
nums[i] += deque[0]
while deque and nums[i] > deque[-1]:
deque.pop()
if nums[i] > 0:
deque.append(nums[i])
#去除超过k步的最大值,为下一步要加的的最大值做准备
if i >= k and deque and deque[0] == nums[i - k]:
deque.popleft()
return max(nums)
|
Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied.
A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.
Example 1:
Input: nums = [10,2,-10,5,20], k = 2
Output: 37
Explanation: The subsequence is [10, 2, 5, 20].
Example 2:
Input: nums = [-1,-2,-3], k = 1
Output: -1
Explanation: The subsequence must be non-empty, so we choose the largest number.
Example 3:
Input: nums = [10,-2,-10,-5,20], k = 2
Output: 23
Explanation: The subsequence is [10, -2, -5, 20].
Constraints:
1 <= k <= nums.length <= 10^5
-10^4 <= nums[i] <= 10^4
|
class Solution:
def constrainedSubsetSum(self, nums: List[int], k: int) -> int:
res = -sys.maxsize
n = len(nums)
dp = [0]*(n+1)
dq = collections.deque()
for i in range(n):
if not dq:
dp[i+1] = nums[i]
else:
dp[i+1] = max(nums[i], dq[0] + nums[i])
dq.append(dp[i+1])
while len(dq) > k:
dq.popleft()
while len(dq) > 1 and dq[0] <= dq[-1]:
dq.popleft()
res = max(res, dp[i+1])
return res
|
Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied.
A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.
Example 1:
Input: nums = [10,2,-10,5,20], k = 2
Output: 37
Explanation: The subsequence is [10, 2, 5, 20].
Example 2:
Input: nums = [-1,-2,-3], k = 1
Output: -1
Explanation: The subsequence must be non-empty, so we choose the largest number.
Example 3:
Input: nums = [10,-2,-10,-5,20], k = 2
Output: 23
Explanation: The subsequence is [10, -2, -5, 20].
Constraints:
1 <= k <= nums.length <= 10^5
-10^4 <= nums[i] <= 10^4
|
from typing import List
import collections
class Solution:
def constrainedSubsetSum(self, nums: List[int], k: int) -> int:
maxx = list(nums)
deque = collections.deque()
for i in range(len(nums)):
if deque:
maxx[i] += deque[0]
while deque and maxx[i] > deque[-1]:
deque.pop()
if maxx[i] > 0:
deque.append(maxx[i])
if i >= k and deque and deque[0] == maxx[i - k]:
deque.popleft()
return max(maxx)
|
Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied.
A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.
Example 1:
Input: nums = [10,2,-10,5,20], k = 2
Output: 37
Explanation: The subsequence is [10, 2, 5, 20].
Example 2:
Input: nums = [-1,-2,-3], k = 1
Output: -1
Explanation: The subsequence must be non-empty, so we choose the largest number.
Example 3:
Input: nums = [10,-2,-10,-5,20], k = 2
Output: 23
Explanation: The subsequence is [10, -2, -5, 20].
Constraints:
1 <= k <= nums.length <= 10^5
-10^4 <= nums[i] <= 10^4
|
class Solution:
def constrainedSubsetSum(self, nums: List[int], k: int) -> int:
rec = -nums[0]
heap = [(-nums[0], 0)]
for j, n in enumerate(nums[1:]):
while j+1-heap[0][1] > k:
heapq.heappop(heap)
cand = -n + heap[0][0] if heap[0][0] <= 0 else -n
rec = min(rec, cand)
heapq.heappush(heap, (cand, j+1))
return -rec
|
Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied.
A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.
Example 1:
Input: nums = [10,2,-10,5,20], k = 2
Output: 37
Explanation: The subsequence is [10, 2, 5, 20].
Example 2:
Input: nums = [-1,-2,-3], k = 1
Output: -1
Explanation: The subsequence must be non-empty, so we choose the largest number.
Example 3:
Input: nums = [10,-2,-10,-5,20], k = 2
Output: 23
Explanation: The subsequence is [10, -2, -5, 20].
Constraints:
1 <= k <= nums.length <= 10^5
-10^4 <= nums[i] <= 10^4
|
class MonoQ:
def __init__(self,k):
self.k = k
self.m = []
def add(self,a,solution):
while len(self.m) > 0:
if solution[a] > solution[self.m[-1]]:
self.m.pop()
else:
break
self.m.append(a)
def grab(self, a, solution, nums):
if len(self.m) > 0:
if self.m[0] > a+self.k:
self.m = self.m[1:]
return max(nums[a],nums[a]+solution[self.m[0]])
else:
return nums[a]
class Solution:
def constrainedSubsetSum(self, nums: List[int], k: int) -> int:
n = len(nums)
solution = [0]*n
m = MonoQ(k)
for i in range(n-1,-1,-1):
solution[i] = m.grab(i,solution,nums)
m.add(i,solution)
return max(solution)
|
Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied.
A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.
Example 1:
Input: nums = [10,2,-10,5,20], k = 2
Output: 37
Explanation: The subsequence is [10, 2, 5, 20].
Example 2:
Input: nums = [-1,-2,-3], k = 1
Output: -1
Explanation: The subsequence must be non-empty, so we choose the largest number.
Example 3:
Input: nums = [10,-2,-10,-5,20], k = 2
Output: 23
Explanation: The subsequence is [10, -2, -5, 20].
Constraints:
1 <= k <= nums.length <= 10^5
-10^4 <= nums[i] <= 10^4
|
import heapq
class Solution:
def constrainedSubsetSum(self, nums: List[int], k: int) -> int:
heap = []
n = len(nums)
dp = [None] * n
for i in range(n):
best = None
while len(heap) > 0:
val, idx = heap[0]
val *= (-1)
if i - idx <= k:
best = val
break
heapq.heappop(heap)
dp[i] = nums[i]
if best is not None and dp[i] < best + nums[i]:
dp[i] = best + nums[i]
#print(dp)
heapq.heappush(heap, (-dp[i], i))
return max(dp)
|
Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied.
A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.
Example 1:
Input: nums = [10,2,-10,5,20], k = 2
Output: 37
Explanation: The subsequence is [10, 2, 5, 20].
Example 2:
Input: nums = [-1,-2,-3], k = 1
Output: -1
Explanation: The subsequence must be non-empty, so we choose the largest number.
Example 3:
Input: nums = [10,-2,-10,-5,20], k = 2
Output: 23
Explanation: The subsequence is [10, -2, -5, 20].
Constraints:
1 <= k <= nums.length <= 10^5
-10^4 <= nums[i] <= 10^4
|
from heapq import heappush, heappop
class Solution:
def constrainedSubsetSum(self, nums: List[int], k: int) -> int:
# [-max_sum, idx]
res = -float('inf')
queue = []
for i, x in enumerate(nums):
while queue and queue[0][1] < i - k:
heappop(queue)
if queue:
y = x - queue[0][0]
else:
y = x
res = max(res, y)
if y > 0:
heappush(queue, [-y, i])
return res
|
Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied.
A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.
Example 1:
Input: nums = [10,2,-10,5,20], k = 2
Output: 37
Explanation: The subsequence is [10, 2, 5, 20].
Example 2:
Input: nums = [-1,-2,-3], k = 1
Output: -1
Explanation: The subsequence must be non-empty, so we choose the largest number.
Example 3:
Input: nums = [10,-2,-10,-5,20], k = 2
Output: 23
Explanation: The subsequence is [10, -2, -5, 20].
Constraints:
1 <= k <= nums.length <= 10^5
-10^4 <= nums[i] <= 10^4
|
class Solution:
def constrainedSubsetSum(self, nums: List[int], k: int) -> int:
max_queue = collections.deque([0,])
max_sum = nums[0]
for i in range(1, len(nums)):
while max(0,i-k)>max_queue[0]:
max_queue.popleft()
nums[i] += max(0, nums[max_queue[0]])
max_sum = max(max_sum, nums[i])
while max_queue and nums[max_queue[-1]]<nums[i]:
max_queue.pop()
max_queue.append(i)
return max_sum
|
Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied.
A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.
Example 1:
Input: nums = [10,2,-10,5,20], k = 2
Output: 37
Explanation: The subsequence is [10, 2, 5, 20].
Example 2:
Input: nums = [-1,-2,-3], k = 1
Output: -1
Explanation: The subsequence must be non-empty, so we choose the largest number.
Example 3:
Input: nums = [10,-2,-10,-5,20], k = 2
Output: 23
Explanation: The subsequence is [10, -2, -5, 20].
Constraints:
1 <= k <= nums.length <= 10^5
-10^4 <= nums[i] <= 10^4
|
from heapq import heappush, heappop
class Solution:
def constrainedSubsetSum(self, nums: List[int], k: int) -> int:
res = -float('inf')
queue = list()
for i, x in enumerate(nums):
while queue and queue[0][1] < i - k:
heappop(queue)
if queue:
val, idx = queue[0]
if val < 0:
x -= val
heappush(queue, [-x, i])
res = max(res, x)
return res
|
Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied.
A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.
Example 1:
Input: nums = [10,2,-10,5,20], k = 2
Output: 37
Explanation: The subsequence is [10, 2, 5, 20].
Example 2:
Input: nums = [-1,-2,-3], k = 1
Output: -1
Explanation: The subsequence must be non-empty, so we choose the largest number.
Example 3:
Input: nums = [10,-2,-10,-5,20], k = 2
Output: 23
Explanation: The subsequence is [10, -2, -5, 20].
Constraints:
1 <= k <= nums.length <= 10^5
-10^4 <= nums[i] <= 10^4
|
import collections
class Solution:
def constrainedSubsetSum(self, nums: List[int], k: int) -> int:
# Like jump game
# At nums[i], add the max of [num[i-k], ... num[i-1], 0]
# this can be done by deque with max k
sol = -float('inf')
n = len(nums)
maxque = collections.deque([(-1,0)])
for i in range(n):
max_i = max(maxque[0][1],0) + nums[i]
sol = max(sol, max_i)
while maxque:
if maxque[-1][1] < max_i:
maxque.pop()
else:
break
maxque.append((i,max_i))
if maxque[0][0] <= i-k:
maxque.popleft()
return sol
|
Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied.
A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.
Example 1:
Input: nums = [10,2,-10,5,20], k = 2
Output: 37
Explanation: The subsequence is [10, 2, 5, 20].
Example 2:
Input: nums = [-1,-2,-3], k = 1
Output: -1
Explanation: The subsequence must be non-empty, so we choose the largest number.
Example 3:
Input: nums = [10,-2,-10,-5,20], k = 2
Output: 23
Explanation: The subsequence is [10, -2, -5, 20].
Constraints:
1 <= k <= nums.length <= 10^5
-10^4 <= nums[i] <= 10^4
|
class Solution:
def constrainedSubsetSum(self, nums: List[int], k: int) -> int:
dp = [n for n in nums]
heap = [(-nums[0], 0)]
for j in range(1, len(nums)):
while heap[0][1] < j - k:
heapq.heappop(heap)
dp[j] = max(dp[j], -heap[0][0] + nums[j])
heapq.heappush(heap, (-dp[j], j))
return max(dp)
|
Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied.
A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.
Example 1:
Input: nums = [10,2,-10,5,20], k = 2
Output: 37
Explanation: The subsequence is [10, 2, 5, 20].
Example 2:
Input: nums = [-1,-2,-3], k = 1
Output: -1
Explanation: The subsequence must be non-empty, so we choose the largest number.
Example 3:
Input: nums = [10,-2,-10,-5,20], k = 2
Output: 23
Explanation: The subsequence is [10, -2, -5, 20].
Constraints:
1 <= k <= nums.length <= 10^5
-10^4 <= nums[i] <= 10^4
|
class Solution:
def constrainedSubsetSum(self, nums: List[int], k: int) -> int:
n=len(nums)
dp=[-sys.maxsize]*n
dq=collections.deque([])
dp[n-1]=nums[n-1]
res=dp[n-1]
for i in range(n-2,-1,-1):
while(len(dq)!=0 and dp[i+1]>dp[dq[-1]]):
dq.pop()
while(len(dq)!=0 and dq[0]>i+k):
dq.popleft()
dq.append(i+1)
dp[i]=max(dp[i],nums[i],nums[i]+dp[dq[0]])
res=max(res,dp[i])
return res
|
Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied.
A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.
Example 1:
Input: nums = [10,2,-10,5,20], k = 2
Output: 37
Explanation: The subsequence is [10, 2, 5, 20].
Example 2:
Input: nums = [-1,-2,-3], k = 1
Output: -1
Explanation: The subsequence must be non-empty, so we choose the largest number.
Example 3:
Input: nums = [10,-2,-10,-5,20], k = 2
Output: 23
Explanation: The subsequence is [10, -2, -5, 20].
Constraints:
1 <= k <= nums.length <= 10^5
-10^4 <= nums[i] <= 10^4
|
class Solution:
def constrainedSubsetSum(self, A: List[int], k: int) -> int:
d = collections.deque()
for i in range(len(A)):
A[i] += d[0] if d else 0
while d and A[i] > d[-1]:
d.pop()
if A[i] > 0:
d.append(A[i])
if i >= k and d and d[0] == A[i-k]:
d.popleft()
return max(A)
|
Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied.
A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.
Example 1:
Input: nums = [10,2,-10,5,20], k = 2
Output: 37
Explanation: The subsequence is [10, 2, 5, 20].
Example 2:
Input: nums = [-1,-2,-3], k = 1
Output: -1
Explanation: The subsequence must be non-empty, so we choose the largest number.
Example 3:
Input: nums = [10,-2,-10,-5,20], k = 2
Output: 23
Explanation: The subsequence is [10, -2, -5, 20].
Constraints:
1 <= k <= nums.length <= 10^5
-10^4 <= nums[i] <= 10^4
|
class Solution:
def constrainedSubsetSum(self, nums: List[int], k: int) -> int:
pq = [(-nums[0], 0)]
res = nums[0]
for i in range(1, len(nums)):
rm = i - k - 1
while pq[0][1] <= rm:
heapq.heappop(pq)
cur = max(-pq[0][0], 0) + nums[i]
res = max(res, cur)
heapq.heappush(pq, (-cur, i))
return res
|
Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied.
A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.
Example 1:
Input: nums = [10,2,-10,5,20], k = 2
Output: 37
Explanation: The subsequence is [10, 2, 5, 20].
Example 2:
Input: nums = [-1,-2,-3], k = 1
Output: -1
Explanation: The subsequence must be non-empty, so we choose the largest number.
Example 3:
Input: nums = [10,-2,-10,-5,20], k = 2
Output: 23
Explanation: The subsequence is [10, -2, -5, 20].
Constraints:
1 <= k <= nums.length <= 10^5
-10^4 <= nums[i] <= 10^4
|
import heapq
class Solution:
def constrainedSubsetSum(self, nums: List[int], k: int) -> int:
n = len(nums)
# dp: walk backward, optimized dp process
ans = nums.copy()
q = []
for i in range(n - 1, -1, -1):
# armortized O(1)
while q and q[0][1] - i > k:
heapq.heappop(q)
if q:
ans[i] += max(0, -q[0][0])
heapq.heappush(q, (-ans[i], i))
return max(ans)
|
Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied.
A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.
Example 1:
Input: nums = [10,2,-10,5,20], k = 2
Output: 37
Explanation: The subsequence is [10, 2, 5, 20].
Example 2:
Input: nums = [-1,-2,-3], k = 1
Output: -1
Explanation: The subsequence must be non-empty, so we choose the largest number.
Example 3:
Input: nums = [10,-2,-10,-5,20], k = 2
Output: 23
Explanation: The subsequence is [10, -2, -5, 20].
Constraints:
1 <= k <= nums.length <= 10^5
-10^4 <= nums[i] <= 10^4
|
class Solution:
def constrainedSubsetSum(self, nums: List[int], k: int) -> int:
dp=[-sys.maxsize]*len(nums)
ans=nums[0]
dp[0]=nums[0]
heap=[(-nums[0],0)]
heapq.heapify(heap)
for i in range(1,len(nums)):
bound=i-k
while heap[0][1]<bound:
heapq.heappop(heap)
dp[i]=max(dp[i],nums[i],-heap[0][0]+nums[i])
ans=max(ans,dp[i])
heapq.heappush(heap,(-dp[i],i))
return ans
|
Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied.
A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.
Example 1:
Input: nums = [10,2,-10,5,20], k = 2
Output: 37
Explanation: The subsequence is [10, 2, 5, 20].
Example 2:
Input: nums = [-1,-2,-3], k = 1
Output: -1
Explanation: The subsequence must be non-empty, so we choose the largest number.
Example 3:
Input: nums = [10,-2,-10,-5,20], k = 2
Output: 23
Explanation: The subsequence is [10, -2, -5, 20].
Constraints:
1 <= k <= nums.length <= 10^5
-10^4 <= nums[i] <= 10^4
|
class Solution:
def constrainedSubsetSum(self, nums: List[int], k: int) -> int:
n = len(nums)
q = [(-nums[0], 0)]
res = nums[0]
dp = [0] * n
for i in range(1, n):
while q and i - q[0][1] > k:
heapq.heappop(q)
t = max(nums[i] - q[0][0], nums[i])
res = max(res, t)
heapq.heappush(q, (-t, i))
return res
|
Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied.
A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.
Example 1:
Input: nums = [10,2,-10,5,20], k = 2
Output: 37
Explanation: The subsequence is [10, 2, 5, 20].
Example 2:
Input: nums = [-1,-2,-3], k = 1
Output: -1
Explanation: The subsequence must be non-empty, so we choose the largest number.
Example 3:
Input: nums = [10,-2,-10,-5,20], k = 2
Output: 23
Explanation: The subsequence is [10, -2, -5, 20].
Constraints:
1 <= k <= nums.length <= 10^5
-10^4 <= nums[i] <= 10^4
|
class Solution:
def constrainedSubsetSum(self, nums: List[int], k: int) -> int:
q = collections.deque()
for i in range(len(nums)):
nums[i] += q[0] if q else 0
while q and nums[i] > q[-1]:
q.pop()
if nums[i] > 0:
q.append(nums[i])
if i >= k and q and q[0] == nums[i-k]:
q.popleft()
return max(nums)
|
Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied.
A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.
Example 1:
Input: nums = [10,2,-10,5,20], k = 2
Output: 37
Explanation: The subsequence is [10, 2, 5, 20].
Example 2:
Input: nums = [-1,-2,-3], k = 1
Output: -1
Explanation: The subsequence must be non-empty, so we choose the largest number.
Example 3:
Input: nums = [10,-2,-10,-5,20], k = 2
Output: 23
Explanation: The subsequence is [10, -2, -5, 20].
Constraints:
1 <= k <= nums.length <= 10^5
-10^4 <= nums[i] <= 10^4
|
class Solution:
def constrainedSubsetSum(self, nums: List[int], k: int) -> int:
n = len(nums)
q = collections.deque()
result = nums[0]
for i in range(n):
while q and q[0][1] < i - k:
q.popleft()
a = q[0][0] if q else 0
m = nums[i] + (a if a > 0 else 0)
while q and m >= q[-1][0]:
q.pop()
q.append((m, i))
result = max(result, m)
return result
|
Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied.
A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.
Example 1:
Input: nums = [10,2,-10,5,20], k = 2
Output: 37
Explanation: The subsequence is [10, 2, 5, 20].
Example 2:
Input: nums = [-1,-2,-3], k = 1
Output: -1
Explanation: The subsequence must be non-empty, so we choose the largest number.
Example 3:
Input: nums = [10,-2,-10,-5,20], k = 2
Output: 23
Explanation: The subsequence is [10, -2, -5, 20].
Constraints:
1 <= k <= nums.length <= 10^5
-10^4 <= nums[i] <= 10^4
|
class Solution:
def constrainedSubsetSum(self, nums: List[int], k: int) -> int:
heap = [(-nums[0], 0)]
ret = nums[0]
for i in range(1, len(nums)):
remove = i - k - 1
while remove >= heap[0][1]:
heapq.heappop(heap)
cur = max(0, -heap[0][0]) + nums[i]
ret = max(ret, cur)
heapq.heappush(heap, (-cur, i))
return ret
|
Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied.
A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.
Example 1:
Input: nums = [10,2,-10,5,20], k = 2
Output: 37
Explanation: The subsequence is [10, 2, 5, 20].
Example 2:
Input: nums = [-1,-2,-3], k = 1
Output: -1
Explanation: The subsequence must be non-empty, so we choose the largest number.
Example 3:
Input: nums = [10,-2,-10,-5,20], k = 2
Output: 23
Explanation: The subsequence is [10, -2, -5, 20].
Constraints:
1 <= k <= nums.length <= 10^5
-10^4 <= nums[i] <= 10^4
|
from collections import deque
class Solution:
def constrainedSubsetSum(self, nums: List[int], k: int) -> int:
dp = nums.copy()
ans = dp[0]
monoq = deque()
qsize = 0
for i, num in enumerate(nums):
if i > 0:
dp[i] = max(dp[i], num + monoq[0][0])
ans = max(ans, dp[i])
pops = 1
while monoq and dp[i] > monoq[-1][0]:
_, freq = monoq.pop()
pops += freq
qsize -= freq
monoq.append([dp[i], pops])
qsize += pops
while qsize > k:
extra = qsize - k
if monoq[0][1] > extra:
monoq[0][1] -= extra
qsize = k
else:
_, v = monoq.popleft()
qsize -= v
return ans
|
Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied.
A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.
Example 1:
Input: nums = [10,2,-10,5,20], k = 2
Output: 37
Explanation: The subsequence is [10, 2, 5, 20].
Example 2:
Input: nums = [-1,-2,-3], k = 1
Output: -1
Explanation: The subsequence must be non-empty, so we choose the largest number.
Example 3:
Input: nums = [10,-2,-10,-5,20], k = 2
Output: 23
Explanation: The subsequence is [10, -2, -5, 20].
Constraints:
1 <= k <= nums.length <= 10^5
-10^4 <= nums[i] <= 10^4
|
from collections import deque
class Solution:
def constrainedSubsetSum(self, nums, k):
N, queue = len(nums), deque()
dp = [0] * N
for i, val in enumerate(nums):
if queue and (i - queue[0] > k):
#if i > k and (queue[0] == i - k - 1):
queue.popleft()
#dp[i] = (val + max(dp[queue[0]], 0)) if queue else val
if queue and dp[queue[0]] > 0:
dp[i] = val + dp[queue[0]]
else:
dp[i] = val
while queue and dp[i] >= dp[queue[-1]]:
queue.pop()
queue.append(i)
return max(dp)
from collections import deque
class Solution:
def constrainedSubsetSum(self, nums, k):
if not nums or not k: return 0
if max(nums) <= 0: return max(nums)
if min(nums) >= 0: return sum(nums)
queue, N = deque(), len(nums)
for i in range(N):
#if queue and (i - queue[0] > k):
while queue and queue[0] < i - k:
queue.popleft()
# compute the max sum we can get at index i
if queue:
nums[i] += nums[queue[0]]
# delet all the sequence that smaller than current sum, becaus there will never be
# considers ==> smaller than current sequence, and end before current sequence
while queue and nums[queue[-1]] < nums[i]:
queue.pop()
# if nums[i] < 0, it can't be a useful prefix sum
if nums[i] > 0:
queue.append(i)
return max(nums)
from collections import deque
class Solution:
def constrainedSubsetSum(self, nums, k):
N, queue = len(nums), deque()
dp = [val for val in nums]
for i, val in enumerate(nums):
if queue and (i - queue[0] > k):
queue.popleft()
if queue and dp[queue[0]] > 0:
dp[i] += dp[queue[0]]
while queue and dp[i] >= dp[queue[-1]]:
queue.pop()
queue.append(i)
return max(dp)
|
Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied.
A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.
Example 1:
Input: nums = [10,2,-10,5,20], k = 2
Output: 37
Explanation: The subsequence is [10, 2, 5, 20].
Example 2:
Input: nums = [-1,-2,-3], k = 1
Output: -1
Explanation: The subsequence must be non-empty, so we choose the largest number.
Example 3:
Input: nums = [10,-2,-10,-5,20], k = 2
Output: 23
Explanation: The subsequence is [10, -2, -5, 20].
Constraints:
1 <= k <= nums.length <= 10^5
-10^4 <= nums[i] <= 10^4
|
from collections import deque
class Solution:
def constrainedSubsetSum(self, A: List[int], k: int) -> int:
Q = deque([(0, A[0])]) # decreasing
running_max = A[0]
for i in range(1, len(A)):
if Q[0][0] < i - k:
Q.popleft()
maxsum_of_subseq_ends_at_i = A[i] + max(Q[0][1], 0)
running_max = max(maxsum_of_subseq_ends_at_i, running_max)
while Q and Q[-1][1] <= maxsum_of_subseq_ends_at_i:
Q.pop()
Q.append((i, maxsum_of_subseq_ends_at_i))
return running_max
|
Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied.
A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.
Example 1:
Input: nums = [10,2,-10,5,20], k = 2
Output: 37
Explanation: The subsequence is [10, 2, 5, 20].
Example 2:
Input: nums = [-1,-2,-3], k = 1
Output: -1
Explanation: The subsequence must be non-empty, so we choose the largest number.
Example 3:
Input: nums = [10,-2,-10,-5,20], k = 2
Output: 23
Explanation: The subsequence is [10, -2, -5, 20].
Constraints:
1 <= k <= nums.length <= 10^5
-10^4 <= nums[i] <= 10^4
|
class Solution:
def constrainedSubsetSum(self, nums: List[int], k: int) -> int:
n = len(nums)
dp = [-sys.maxsize] * n
dp[0] = nums[0]
maxDeque = deque()
ans = -sys.maxsize
for j in range(n):
while len(maxDeque) > 0 and j - maxDeque[0] > k:
maxDeque.popleft()
preMax = dp[maxDeque[0]] if len(maxDeque) > 0 else 0
dp[j] = max(preMax + nums[j], nums[j])
ans = max(dp[j], ans)
while len(maxDeque) > 0 and dp[maxDeque[-1]] < dp[j]:
maxDeque.pop()
maxDeque.append(j)
return ans
|
Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied.
A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.
Example 1:
Input: nums = [10,2,-10,5,20], k = 2
Output: 37
Explanation: The subsequence is [10, 2, 5, 20].
Example 2:
Input: nums = [-1,-2,-3], k = 1
Output: -1
Explanation: The subsequence must be non-empty, so we choose the largest number.
Example 3:
Input: nums = [10,-2,-10,-5,20], k = 2
Output: 23
Explanation: The subsequence is [10, -2, -5, 20].
Constraints:
1 <= k <= nums.length <= 10^5
-10^4 <= nums[i] <= 10^4
|
class Solution:
def constrainedSubsetSum(self, nums: List[int], k: int) -> int:
dp, res = collections.deque(), -float('inf')
for i, n in enumerate(nums):
if dp and dp[0][0] < i - k:
dp.popleft()
cur = n + (0 if not dp else dp[0][1])
res = max(res, cur)
if cur > 0:
while dp and dp[-1][1] <= cur:
dp.pop()
dp.append((i, cur))
# print('dp', dp)
return res
|
Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied.
A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.
Example 1:
Input: nums = [10,2,-10,5,20], k = 2
Output: 37
Explanation: The subsequence is [10, 2, 5, 20].
Example 2:
Input: nums = [-1,-2,-3], k = 1
Output: -1
Explanation: The subsequence must be non-empty, so we choose the largest number.
Example 3:
Input: nums = [10,-2,-10,-5,20], k = 2
Output: 23
Explanation: The subsequence is [10, -2, -5, 20].
Constraints:
1 <= k <= nums.length <= 10^5
-10^4 <= nums[i] <= 10^4
|
class Solution:
def constrainedSubsetSum(self, nums: List[int], k: int) -> int:
n=len(nums)
dp=[0]*n
remove=collections.defaultdict(int)
h=[]
def get_b():
if not h:
return 0
b=heapq.heappop(h)
while remove[b]>0:
remove[b]-=1
b=heapq.heappop(h)
heapq.heappush(h,b)
return -b
for i,d in enumerate(nums):
if i>k:
remove[-dp[i-k-1]]+=1
dp[i]=max(get_b(),0)+d
heapq.heappush(h,-dp[i])
return max(dp)
|
Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied.
A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.
Example 1:
Input: nums = [10,2,-10,5,20], k = 2
Output: 37
Explanation: The subsequence is [10, 2, 5, 20].
Example 2:
Input: nums = [-1,-2,-3], k = 1
Output: -1
Explanation: The subsequence must be non-empty, so we choose the largest number.
Example 3:
Input: nums = [10,-2,-10,-5,20], k = 2
Output: 23
Explanation: The subsequence is [10, -2, -5, 20].
Constraints:
1 <= k <= nums.length <= 10^5
-10^4 <= nums[i] <= 10^4
|
class Solution:
def constrainedSubsetSum(self, nums: List[int], k: int) -> int:
n = len(nums)
q = collections.deque()
result = nums[0]
for i in range(n):
while q and q[0][1] < i - k:
q.popleft()
a = q[0][0] if q else 0
m = nums[i] + (a if a > 0 else 0)
if m > 0:
while q and m >= q[-1][0]:
q.pop()
q.append((m, i))
result = max(result, m)
return result
|
Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied.
A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.
Example 1:
Input: nums = [10,2,-10,5,20], k = 2
Output: 37
Explanation: The subsequence is [10, 2, 5, 20].
Example 2:
Input: nums = [-1,-2,-3], k = 1
Output: -1
Explanation: The subsequence must be non-empty, so we choose the largest number.
Example 3:
Input: nums = [10,-2,-10,-5,20], k = 2
Output: 23
Explanation: The subsequence is [10, -2, -5, 20].
Constraints:
1 <= k <= nums.length <= 10^5
-10^4 <= nums[i] <= 10^4
|
class Solution:
def constrainedSubsetSum(self, nums: List[int], k: int) -> int:
dp = [0 - sys.maxsize for i in range(len(nums))]
heap = []
dp[0] = nums[0]
heapq.heappush(heap, (0-nums[0], 0))
for i in range(1,len(nums)):
while len(heap) and heap[0][1] < i - k:
heapq.heappop(heap)
dp[i] = max(dp[i], nums[i] + max(0, 0 - heap[0][0] if len(heap) else 0))
heapq.heappush(heap, (0 - dp[i], i))
return max(dp)
|
Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied.
A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.
Example 1:
Input: nums = [10,2,-10,5,20], k = 2
Output: 37
Explanation: The subsequence is [10, 2, 5, 20].
Example 2:
Input: nums = [-1,-2,-3], k = 1
Output: -1
Explanation: The subsequence must be non-empty, so we choose the largest number.
Example 3:
Input: nums = [10,-2,-10,-5,20], k = 2
Output: 23
Explanation: The subsequence is [10, -2, -5, 20].
Constraints:
1 <= k <= nums.length <= 10^5
-10^4 <= nums[i] <= 10^4
|
class Solution:
def constrainedSubsetSum(self, nums: List[int], k: int) -> int:
n = len(nums)
heap = [(-nums[0], 0)]
result = nums[0]
for i in range(1, n):
while heap and heap[0][1] < i - k:
heapq.heappop(heap)
a = -heap[0][0]
m = nums[i] + (a if a > 0 else 0)
heapq.heappush(heap, (-m, i))
result = max(result, m)
return result
|
Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied.
A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.
Example 1:
Input: nums = [10,2,-10,5,20], k = 2
Output: 37
Explanation: The subsequence is [10, 2, 5, 20].
Example 2:
Input: nums = [-1,-2,-3], k = 1
Output: -1
Explanation: The subsequence must be non-empty, so we choose the largest number.
Example 3:
Input: nums = [10,-2,-10,-5,20], k = 2
Output: 23
Explanation: The subsequence is [10, -2, -5, 20].
Constraints:
1 <= k <= nums.length <= 10^5
-10^4 <= nums[i] <= 10^4
|
from collections import deque
class Solution:
def constrainedSubsetSum(self, nums: List[int], k: int) -> int:
que = deque()
for ind in range(len(nums)):
nums[ind] += que[0] if que else 0
while que and nums[ind] > que[-1]:
que.pop()
if nums[ind] > 0:
que.append(nums[ind])
if que and ind >= k and que[0] == nums[ind-k]:
que.popleft()
return max(nums)
|
Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied.
A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.
Example 1:
Input: nums = [10,2,-10,5,20], k = 2
Output: 37
Explanation: The subsequence is [10, 2, 5, 20].
Example 2:
Input: nums = [-1,-2,-3], k = 1
Output: -1
Explanation: The subsequence must be non-empty, so we choose the largest number.
Example 3:
Input: nums = [10,-2,-10,-5,20], k = 2
Output: 23
Explanation: The subsequence is [10, -2, -5, 20].
Constraints:
1 <= k <= nums.length <= 10^5
-10^4 <= nums[i] <= 10^4
|
from collections import deque
class Solution:
def constrainedSubsetSum(self, nums, k):
#if max(nums) <= 0: return max(nums) # optimization
#if min(nums) >= 0: return sum(nums) # optimization
N, queue = len(nums), deque()
dp = [val for val in nums]
for i, val in enumerate(nums):
if queue and (i - queue[0] > k):
queue.popleft()
if queue and dp[queue[0]] > 0:
dp[i] += dp[queue[0]]
while queue and dp[i] >= dp[queue[-1]]:
queue.pop()
queue.append(i)
return max(dp)
|
Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied.
A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.
Example 1:
Input: nums = [10,2,-10,5,20], k = 2
Output: 37
Explanation: The subsequence is [10, 2, 5, 20].
Example 2:
Input: nums = [-1,-2,-3], k = 1
Output: -1
Explanation: The subsequence must be non-empty, so we choose the largest number.
Example 3:
Input: nums = [10,-2,-10,-5,20], k = 2
Output: 23
Explanation: The subsequence is [10, -2, -5, 20].
Constraints:
1 <= k <= nums.length <= 10^5
-10^4 <= nums[i] <= 10^4
|
class Solution:
def constrainedSubsetSum(self, nums: List[int], k: int) -> int:
q = deque()
q.append((nums[0],0))
max_sum = nums[0]
for i in range(1,len(nums)):
while q and q[0][1] < i - k:
q.popleft()
next_val = max(nums[i], nums[i] + q[0][0])
while q and q[-1][0] < next_val:
q.pop()
q.append((next_val,i))
max_sum = max(max_sum, q[0][0])
return max_sum
|
Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied.
A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.
Example 1:
Input: nums = [10,2,-10,5,20], k = 2
Output: 37
Explanation: The subsequence is [10, 2, 5, 20].
Example 2:
Input: nums = [-1,-2,-3], k = 1
Output: -1
Explanation: The subsequence must be non-empty, so we choose the largest number.
Example 3:
Input: nums = [10,-2,-10,-5,20], k = 2
Output: 23
Explanation: The subsequence is [10, -2, -5, 20].
Constraints:
1 <= k <= nums.length <= 10^5
-10^4 <= nums[i] <= 10^4
|
class Solution:
def constrainedSubsetSum(self, nums: List[int], k: int) -> int:
deque = []
for i, num in enumerate(nums):
while(deque and nums[deque[-1]] < 0):
deque.pop()
while(deque and deque[0] < i - k):
deque.pop(0)
if deque:
nums[i] = nums[deque[0]] + num
while(deque and nums[deque[-1]] < nums[i]):
deque.pop()
deque.append(i)
return max(nums)
|
Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied.
A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.
Example 1:
Input: nums = [10,2,-10,5,20], k = 2
Output: 37
Explanation: The subsequence is [10, 2, 5, 20].
Example 2:
Input: nums = [-1,-2,-3], k = 1
Output: -1
Explanation: The subsequence must be non-empty, so we choose the largest number.
Example 3:
Input: nums = [10,-2,-10,-5,20], k = 2
Output: 23
Explanation: The subsequence is [10, -2, -5, 20].
Constraints:
1 <= k <= nums.length <= 10^5
-10^4 <= nums[i] <= 10^4
|
from collections import deque
class Solution:
def constrainedSubsetSum(self, nums: List[int], k: int) -> int:
largest = deque()
global_max = float('-inf')
for i, num in enumerate(nums):
if largest and largest[-1][1] < i - k: largest.pop()
curr = num + max(0, largest[-1][0] if largest else 0)
while largest and curr > largest[0][0]:
largest.popleft()
global_max = max(global_max, curr)
largest.appendleft((curr, i))
return global_max
|
Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied.
A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.
Example 1:
Input: nums = [10,2,-10,5,20], k = 2
Output: 37
Explanation: The subsequence is [10, 2, 5, 20].
Example 2:
Input: nums = [-1,-2,-3], k = 1
Output: -1
Explanation: The subsequence must be non-empty, so we choose the largest number.
Example 3:
Input: nums = [10,-2,-10,-5,20], k = 2
Output: 23
Explanation: The subsequence is [10, -2, -5, 20].
Constraints:
1 <= k <= nums.length <= 10^5
-10^4 <= nums[i] <= 10^4
|
from collections import deque
class Solution:
def constrainedSubsetSum(self, A: List[int], k: int) -> int:
deque = collections.deque()
for i in range(len(A)):
A[i] += deque[0] if deque else 0
while len(deque) and A[i] > deque[-1]:
deque.pop()
if A[i] > 0:
deque.append(A[i])
if i >= k and deque and deque[0] == A[i - k]:
deque.popleft()
return max(A)
|
Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied.
A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.
Example 1:
Input: nums = [10,2,-10,5,20], k = 2
Output: 37
Explanation: The subsequence is [10, 2, 5, 20].
Example 2:
Input: nums = [-1,-2,-3], k = 1
Output: -1
Explanation: The subsequence must be non-empty, so we choose the largest number.
Example 3:
Input: nums = [10,-2,-10,-5,20], k = 2
Output: 23
Explanation: The subsequence is [10, -2, -5, 20].
Constraints:
1 <= k <= nums.length <= 10^5
-10^4 <= nums[i] <= 10^4
|
class Solution:
def constrainedSubsetSum(self, nums: List[int], k: int) -> int:
q = deque()
q.append((nums[0],0))
max_sum = nums[0]
for i in range(1,len(nums)):
while q and q[0][1] < i - k:
q.popleft()
next_val = nums[i]
if q and q[0][0] >= 0:
next_val += q[0][0]
while q and q[-1][0] < next_val:
q.pop()
q.append((next_val,i))
max_sum = max(max_sum, q[0][0])
return max_sum
|
Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied.
A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.
Example 1:
Input: nums = [10,2,-10,5,20], k = 2
Output: 37
Explanation: The subsequence is [10, 2, 5, 20].
Example 2:
Input: nums = [-1,-2,-3], k = 1
Output: -1
Explanation: The subsequence must be non-empty, so we choose the largest number.
Example 3:
Input: nums = [10,-2,-10,-5,20], k = 2
Output: 23
Explanation: The subsequence is [10, -2, -5, 20].
Constraints:
1 <= k <= nums.length <= 10^5
-10^4 <= nums[i] <= 10^4
|
class Solution:
def constrainedSubsetSum(self, nums: List[int], k: int) -> int:
dp=collections.deque([(nums[0],0)])
ans=nums[0]
for i in range(1,len(nums)):
new = nums[i] + max(0,dp[0][0])
while dp and dp[0][1]<=i-k:
dp.popleft()
while dp and new>=dp[-1][0]:
dp.pop()
dp.append((new,i))
ans=max(ans,new)
return ans
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.