Datasets:

inputs
stringlengths
50
14k
targets
stringlengths
4
655k
Given an array A of integers, return the length of the longest arithmetic subsequence in A. Recall that a subsequence of A is a list A[i_1], A[i_2], ..., A[i_k] with 0 <= i_1 < i_2 < ... < i_k <= A.length - 1, and that a sequence B is arithmetic if B[i+1] - B[i] are all the same value (for 0 <= i < B.length - 1).   Example 1: Input: A = [3,6,9,12] Output: 4 Explanation: The whole array is an arithmetic sequence with steps of length = 3. Example 2: Input: A = [9,4,7,2,10] Output: 3 Explanation: The longest arithmetic subsequence is [4,7,10]. Example 3: Input: A = [20,1,15,3,10,5,8] Output: 4 Explanation: The longest arithmetic subsequence is [20,15,10,5].   Constraints: 2 <= A.length <= 1000 0 <= A[i] <= 500
class Solution: def longestArithSeqLength(self, A: List[int]) -> int: a = A n = len(a) count = [{} for i in range(n)] for i in range(1,n): for j in range(i): diff = a[i] - a[j] if diff in count[j]: count[i][diff] = 1 + count[j][diff] else: count[i][diff] = 1 max_val = 0 for item in count: if item: max_val = max(max_val, max(item.values())) return max_val+1
Given an array A of integers, return the length of the longest arithmetic subsequence in A. Recall that a subsequence of A is a list A[i_1], A[i_2], ..., A[i_k] with 0 <= i_1 < i_2 < ... < i_k <= A.length - 1, and that a sequence B is arithmetic if B[i+1] - B[i] are all the same value (for 0 <= i < B.length - 1).   Example 1: Input: A = [3,6,9,12] Output: 4 Explanation: The whole array is an arithmetic sequence with steps of length = 3. Example 2: Input: A = [9,4,7,2,10] Output: 3 Explanation: The longest arithmetic subsequence is [4,7,10]. Example 3: Input: A = [20,1,15,3,10,5,8] Output: 4 Explanation: The longest arithmetic subsequence is [20,15,10,5].   Constraints: 2 <= A.length <= 1000 0 <= A[i] <= 500
class Solution: def longestArithSeqLength(self, A: List[int]) -> int: length = len(A) onleft = set() onright = [0 for _ in range(501)] toextend = [{} for _ in range(501)] res = 2 for v in A: onright[v] += 1 for i in range(0, length): val = A[i] tex = toextend[val] onright[val] -= 1 for lval in onleft: diff = val - lval nextval = val + diff if nextval > 500 or nextval < 0 or onright[nextval] == 0: continue c = tex.get(diff, 2) + 1 if c > res: res = c else: ending = (res - c) * diff + nextval if ending > 500 or ending < 0 or onright[ending] == 0: continue toextend[nextval][diff] = c onleft.add(val) return res
Given an array A of integers, return the length of the longest arithmetic subsequence in A. Recall that a subsequence of A is a list A[i_1], A[i_2], ..., A[i_k] with 0 <= i_1 < i_2 < ... < i_k <= A.length - 1, and that a sequence B is arithmetic if B[i+1] - B[i] are all the same value (for 0 <= i < B.length - 1).   Example 1: Input: A = [3,6,9,12] Output: 4 Explanation: The whole array is an arithmetic sequence with steps of length = 3. Example 2: Input: A = [9,4,7,2,10] Output: 3 Explanation: The longest arithmetic subsequence is [4,7,10]. Example 3: Input: A = [20,1,15,3,10,5,8] Output: 4 Explanation: The longest arithmetic subsequence is [20,15,10,5].   Constraints: 2 <= A.length <= 1000 0 <= A[i] <= 500
class Solution: def longestArithSeqLength(self, A: List[int]) -> int: n = len(A) dp = [[2] * n for i in range(n)] index = [-1] * 501 res = 2 for i in range(n): for j in range(i+1, n): first = 2 * A[i] - A[j] if first < 0 or first >= 500 or index[first] == -1: continue dp[i][j] = dp[index[first]][i] + 1 res = max(res, dp[i][j]) index[A[i]] = i return res
Given an array A of integers, return the length of the longest arithmetic subsequence in A. Recall that a subsequence of A is a list A[i_1], A[i_2], ..., A[i_k] with 0 <= i_1 < i_2 < ... < i_k <= A.length - 1, and that a sequence B is arithmetic if B[i+1] - B[i] are all the same value (for 0 <= i < B.length - 1).   Example 1: Input: A = [3,6,9,12] Output: 4 Explanation: The whole array is an arithmetic sequence with steps of length = 3. Example 2: Input: A = [9,4,7,2,10] Output: 3 Explanation: The longest arithmetic subsequence is [4,7,10]. Example 3: Input: A = [20,1,15,3,10,5,8] Output: 4 Explanation: The longest arithmetic subsequence is [20,15,10,5].   Constraints: 2 <= A.length <= 1000 0 <= A[i] <= 500
class Solution: def longestArithSeqLength(self, A: List[int]) -> int: size = len(A) if size <= 1: return size nums = [{} for _ in range(size)] for i in range(1, size): for j in range(0, i): diff = A[i] - A[j] if diff in nums[j]: nums[i][diff] = nums[j][diff]+1 else: nums[i][diff] = 2 max_num = 0 for i in range(1, size): max_num = max(max_num, max(nums[i].values())) return max_num
Given an array A of integers, return the length of the longest arithmetic subsequence in A. Recall that a subsequence of A is a list A[i_1], A[i_2], ..., A[i_k] with 0 <= i_1 < i_2 < ... < i_k <= A.length - 1, and that a sequence B is arithmetic if B[i+1] - B[i] are all the same value (for 0 <= i < B.length - 1).   Example 1: Input: A = [3,6,9,12] Output: 4 Explanation: The whole array is an arithmetic sequence with steps of length = 3. Example 2: Input: A = [9,4,7,2,10] Output: 3 Explanation: The longest arithmetic subsequence is [4,7,10]. Example 3: Input: A = [20,1,15,3,10,5,8] Output: 4 Explanation: The longest arithmetic subsequence is [20,15,10,5].   Constraints: 2 <= A.length <= 1000 0 <= A[i] <= 500
class Solution: def longestArithSeqLength(self, A): dp = dict() for endi, endv in enumerate(A[1:], start = 1): for starti, startv in enumerate(A[:endi]): diff = endv - startv if (starti, diff) in dp: dp[(endi, diff)] = dp[(starti, diff)] + 1 else: dp[(endi, diff)] = 2 return max(dp.values()) class Solution: def longestArithSeqLength(self, A): dp = dict() for starti, startv in enumerate(A): for endi, endv in enumerate(A[starti+1:], start = starti+1): diff = endv - startv if (starti, diff) in dp: dp[(endi, diff)] = dp[(starti, diff)] + 1 else: dp[(endi, diff)] = 2 return max(dp.values()) class Solution: def longestArithSeqLength(self, A): N = len(A) dp = [{0:1} for _ in range(N)] for end in range(1, N): for start in range(end): diff = A[end] - A[start] if diff in dp[start]: dp[end][diff] = dp[start][diff] + 1 else: dp[end][diff] = 2 return max(max(dp[end].values()) for end in range(1, N))
Given an array A of integers, return the length of the longest arithmetic subsequence in A. Recall that a subsequence of A is a list A[i_1], A[i_2], ..., A[i_k] with 0 <= i_1 < i_2 < ... < i_k <= A.length - 1, and that a sequence B is arithmetic if B[i+1] - B[i] are all the same value (for 0 <= i < B.length - 1).   Example 1: Input: A = [3,6,9,12] Output: 4 Explanation: The whole array is an arithmetic sequence with steps of length = 3. Example 2: Input: A = [9,4,7,2,10] Output: 3 Explanation: The longest arithmetic subsequence is [4,7,10]. Example 3: Input: A = [20,1,15,3,10,5,8] Output: 4 Explanation: The longest arithmetic subsequence is [20,15,10,5].   Constraints: 2 <= A.length <= 1000 0 <= A[i] <= 500
from collections import defaultdict, Counter class Solution: def longestArithSeqLength(self, A: List[int]) -> int: dp = defaultdict(lambda: defaultdict(lambda: 1)) best = 0 for i in range(len(A)): num = A[i] for prev_num in list(dp.keys()): step = num - prev_num dp[num][step] = max(dp[prev_num][step] + 1, dp[num][step]) best = max(best, dp[num][step]) dp[num][0] = max(dp[num][0], 1) best = max(dp[num][0], best) return best
Given an array A of integers, return the length of the longest arithmetic subsequence in A. Recall that a subsequence of A is a list A[i_1], A[i_2], ..., A[i_k] with 0 <= i_1 < i_2 < ... < i_k <= A.length - 1, and that a sequence B is arithmetic if B[i+1] - B[i] are all the same value (for 0 <= i < B.length - 1).   Example 1: Input: A = [3,6,9,12] Output: 4 Explanation: The whole array is an arithmetic sequence with steps of length = 3. Example 2: Input: A = [9,4,7,2,10] Output: 3 Explanation: The longest arithmetic subsequence is [4,7,10]. Example 3: Input: A = [20,1,15,3,10,5,8] Output: 4 Explanation: The longest arithmetic subsequence is [20,15,10,5].   Constraints: 2 <= A.length <= 1000 0 <= A[i] <= 500
class Solution: def longestArithSeqLength(self, A: List[int]) -> int: dp = {} for i, a2 in enumerate(A[1:], start=1): for j, a1 in enumerate(A[:i]): d = a2 - a1 if (j, d) in dp: dp[i, d] = dp[j, d] + 1 else: dp[i, d] = 2 return max(dp.values()) # dp = {} # for i, a2 in enumerate(A[1:], start=1): # for j, a1 in enumerate(A[:i]): # d = a2 - a1 # if (j, d) in dp: # dp[i, d] = dp[j, d] + 1 # else: # dp[i, d] = 2 # return max(dp.values())
Given an array A of integers, return the length of the longest arithmetic subsequence in A. Recall that a subsequence of A is a list A[i_1], A[i_2], ..., A[i_k] with 0 <= i_1 < i_2 < ... < i_k <= A.length - 1, and that a sequence B is arithmetic if B[i+1] - B[i] are all the same value (for 0 <= i < B.length - 1).   Example 1: Input: A = [3,6,9,12] Output: 4 Explanation: The whole array is an arithmetic sequence with steps of length = 3. Example 2: Input: A = [9,4,7,2,10] Output: 3 Explanation: The longest arithmetic subsequence is [4,7,10]. Example 3: Input: A = [20,1,15,3,10,5,8] Output: 4 Explanation: The longest arithmetic subsequence is [20,15,10,5].   Constraints: 2 <= A.length <= 1000 0 <= A[i] <= 500
class Solution: def longestArithSeqLength(self, A: List[int]) -> int: result = 2 L = len(A) index = [-1] * 2001 dp = [[2] * L for _ in range(L)] for i in range(L - 1): for j in range(i + 1, L): prevVal = 2 * A[i] - A[j] if index[prevVal] == -1: continue else: idx = index[prevVal] if idx == -1: dp[i][j] = 2 else: dp[i][j] = dp[idx][i] + 1 result = max(result, dp[i][j]) index[A[i]] = i return result
Given an array A of integers, return the length of the longest arithmetic subsequence in A. Recall that a subsequence of A is a list A[i_1], A[i_2], ..., A[i_k] with 0 <= i_1 < i_2 < ... < i_k <= A.length - 1, and that a sequence B is arithmetic if B[i+1] - B[i] are all the same value (for 0 <= i < B.length - 1).   Example 1: Input: A = [3,6,9,12] Output: 4 Explanation: The whole array is an arithmetic sequence with steps of length = 3. Example 2: Input: A = [9,4,7,2,10] Output: 3 Explanation: The longest arithmetic subsequence is [4,7,10]. Example 3: Input: A = [20,1,15,3,10,5,8] Output: 4 Explanation: The longest arithmetic subsequence is [20,15,10,5].   Constraints: 2 <= A.length <= 1000 0 <= A[i] <= 500
class Solution: def longestArithSeqLength(self, A: List[int]) -> int: a = len(A) dp = [[0]*a for _ in range(a)] # dp array #print(dp) index = [-1]*20001#index array maximum = 2 for i in range(0,a): dp[i] = [2]*a for j in range(i+1, a): #print(\"A[i]\",A[i],\"A[j]\",A[j] ) first = A[i]*2-A[j] #print(\"first\",first) if first < 0 or index[first]==-1: continue else: #print(\"index[first]\",index[first]) #print(\"dp[index[first]][i]\",dp[index[first]][i]) dp[i][j] = dp[index[first]][i]+1 #print(\"dp[i][j]\",dp[i][j]) maximum = max(maximum,dp[i][j] ) #print(\"max\", maximum) #print(dp) index[A[i]] = i return maximum
Given an array A of integers, return the length of the longest arithmetic subsequence in A. Recall that a subsequence of A is a list A[i_1], A[i_2], ..., A[i_k] with 0 <= i_1 < i_2 < ... < i_k <= A.length - 1, and that a sequence B is arithmetic if B[i+1] - B[i] are all the same value (for 0 <= i < B.length - 1).   Example 1: Input: A = [3,6,9,12] Output: 4 Explanation: The whole array is an arithmetic sequence with steps of length = 3. Example 2: Input: A = [9,4,7,2,10] Output: 3 Explanation: The longest arithmetic subsequence is [4,7,10]. Example 3: Input: A = [20,1,15,3,10,5,8] Output: 4 Explanation: The longest arithmetic subsequence is [20,15,10,5].   Constraints: 2 <= A.length <= 1000 0 <= A[i] <= 500
class Solution: def longestArithSeqLength(self, A: List[int]) -> int: pos_diff_to_length = {} result = 0 for i in range(1, len(A)): for j in range(i): if (j, A[i] - A[j]) in pos_diff_to_length: pos_diff_to_length[(i, A[i] - A[j])] = pos_diff_to_length[(j, A[i] - A[j])] + 1 else: pos_diff_to_length[(i, A[i] - A[j])] = 2 result = max(result, pos_diff_to_length[(i, A[i] - A[j])]) return result
Given an array A of integers, return the length of the longest arithmetic subsequence in A. Recall that a subsequence of A is a list A[i_1], A[i_2], ..., A[i_k] with 0 <= i_1 < i_2 < ... < i_k <= A.length - 1, and that a sequence B is arithmetic if B[i+1] - B[i] are all the same value (for 0 <= i < B.length - 1).   Example 1: Input: A = [3,6,9,12] Output: 4 Explanation: The whole array is an arithmetic sequence with steps of length = 3. Example 2: Input: A = [9,4,7,2,10] Output: 3 Explanation: The longest arithmetic subsequence is [4,7,10]. Example 3: Input: A = [20,1,15,3,10,5,8] Output: 4 Explanation: The longest arithmetic subsequence is [20,15,10,5].   Constraints: 2 <= A.length <= 1000 0 <= A[i] <= 500
class Solution: def longestArithSeqLength(self, A: List[int]) -> int: DP = [0]*len(A) for i in range(len(A)): temp = {} for j in range(i): diff = A[i]-A[j] temp[diff] = DP[j].get(diff, 0)+1 DP[i] = temp return max(max(d.values()) for d in DP if d)+1
Given a non-negative integer N, find the largest number that is less than or equal to N with monotone increasing digits. (Recall that an integer has monotone increasing digits if and only if each pair of adjacent digits x and y satisfy x .) Example 1: Input: N = 10 Output: 9 Example 2: Input: N = 1234 Output: 1234 Example 3: Input: N = 332 Output: 299 Note: N is an integer in the range [0, 10^9].
class Solution: def monotoneIncreasingDigits(self, N): """ :type N: int :rtype: int """ arr = [int(ch) for ch in str(N)] # create array from number 1234 => [1,2,3,4] marker = len(arr) i = len(arr)-2 while i >= 0: if arr[i] > arr[i+1]: marker = i+1 arr[i] -= 1 i-=1 while marker < len(arr): arr[marker] = 9 marker += 1 return int(''.join([str(num) for num in arr])) # # any number 0..9 has always monotone increasing digits # if N < 10: # return N # stack = [] # # create stack of digits 1234 -> [4,3,2,1] # while N: # stack.append(N%10) # N = N // 10 # X = 0 # power_of_10 = len(stack)-1 # right = stack.pop() # while stack: # left = right # right = stack.pop() # if left <= right: # X += left * (10**power_of_10) # power_of_10 -= 1 # else: # X += (left-1) * (10**power_of_10) # X += int('9'*power_of_10) # return self.monotoneIncreasingDigits(X) # # remaining part # X += right # return X
Given a non-negative integer N, find the largest number that is less than or equal to N with monotone increasing digits. (Recall that an integer has monotone increasing digits if and only if each pair of adjacent digits x and y satisfy x .) Example 1: Input: N = 10 Output: 9 Example 2: Input: N = 1234 Output: 1234 Example 3: Input: N = 332 Output: 299 Note: N is an integer in the range [0, 10^9].
class Solution: def monotoneIncreasingDigits(self, N): """ :type N: int :rtype: int """ digits = list(map(int, str(N))) i = 0 while i < len(digits) - 1 and digits[i] <= digits[i+1]: i += 1 while 0 <= i < len(digits) - 1 and digits[i] > digits[i+1]: digits[i] -= 1 i -= 1 digits[i+2:] = '9' * (len(digits) - i - 2) return int(''.join(map(str, digits)))
Given a non-negative integer N, find the largest number that is less than or equal to N with monotone increasing digits. (Recall that an integer has monotone increasing digits if and only if each pair of adjacent digits x and y satisfy x .) Example 1: Input: N = 10 Output: 9 Example 2: Input: N = 1234 Output: 1234 Example 3: Input: N = 332 Output: 299 Note: N is an integer in the range [0, 10^9].
class Solution: def monotoneIncreasingDigits(self, N): """ :type N: int :rtype: int """ n = str(N) pos = 0 for i, char in enumerate(n): if i>0 and int(n[i])<int(n[i-1]): return int("".join(n[:pos])+str(int(n[pos])-1)+"9"*(len(n)-1-pos)) if int(n[pos])>1 else int("9"*(len(n)-1-pos)) elif i>0 and n[i] != n[i-1]: pos = i return N
Given a non-negative integer N, find the largest number that is less than or equal to N with monotone increasing digits. (Recall that an integer has monotone increasing digits if and only if each pair of adjacent digits x and y satisfy x .) Example 1: Input: N = 10 Output: 9 Example 2: Input: N = 1234 Output: 1234 Example 3: Input: N = 332 Output: 299 Note: N is an integer in the range [0, 10^9].
class Solution: def monotoneIncreasingDigits(self, N): """ :type N: int :rtype: int """ NN = ('000000000000000000' + str(N))[-11:] chron = '0' for i in range(10): maxpossible = int(chron[-1]) for fill in range(int(chron[-1]),10): if chron + str(fill)*(10-i) <= NN: maxpossible = fill chron = chron + str(maxpossible) return int(chron)
Given a non-negative integer N, find the largest number that is less than or equal to N with monotone increasing digits. (Recall that an integer has monotone increasing digits if and only if each pair of adjacent digits x and y satisfy x .) Example 1: Input: N = 10 Output: 9 Example 2: Input: N = 1234 Output: 1234 Example 3: Input: N = 332 Output: 299 Note: N is an integer in the range [0, 10^9].
class Solution(object): def monotoneIncreasingDigits(self, N): digits = [] A = list(map(int, str(N))) for i in range(len(A)): for d in range(1, 10): if digits + [d] * (len(A)-i) > A: digits.append(d-1) break else: digits.append(9) return int("".join(map(str, digits)))
Given a non-negative integer N, find the largest number that is less than or equal to N with monotone increasing digits. (Recall that an integer has monotone increasing digits if and only if each pair of adjacent digits x and y satisfy x .) Example 1: Input: N = 10 Output: 9 Example 2: Input: N = 1234 Output: 1234 Example 3: Input: N = 332 Output: 299 Note: N is an integer in the range [0, 10^9].
class Solution: def monotoneIncreasingDigits(self, N): """ :type N: int :rtype: int """ digits = list(int(d) for d in str(N)) for i in range(len(digits)-1, 0, -1): if digits[i] < digits[i-1]: for k in range (i, len(digits)): digits[k] = 9 digits[i-1] -= 1 return int(''.join([str(d) for d in digits]))
Given a non-negative integer N, find the largest number that is less than or equal to N with monotone increasing digits. (Recall that an integer has monotone increasing digits if and only if each pair of adjacent digits x and y satisfy x .) Example 1: Input: N = 10 Output: 9 Example 2: Input: N = 1234 Output: 1234 Example 3: Input: N = 332 Output: 299 Note: N is an integer in the range [0, 10^9].
class Solution(object): def monotoneIncreasingDigits(self, N): """ :type N: int :rtype: int """ l = list(str(N)) length = len(l) for i in range(length): l[i] = ord(l[i]) - ord('0') # get the longest non-decreasing sequence index = -1 for i in range(length-1): if l[i] > l[i+1]: index = i break if index == -1: return N j = -1 # identity which digit to change for i in range(index, -1, -1): j = i if i>0 and l[i] == l[i-1]: continue break # make the change l[j] -= 1 for i in range(j+1, length): l[i] = 9 # get the result res = 0 for i in range(length): res = res*10+l[i] return res
Given a non-negative integer N, find the largest number that is less than or equal to N with monotone increasing digits. (Recall that an integer has monotone increasing digits if and only if each pair of adjacent digits x and y satisfy x .) Example 1: Input: N = 10 Output: 9 Example 2: Input: N = 1234 Output: 1234 Example 3: Input: N = 332 Output: 299 Note: N is an integer in the range [0, 10^9].
class Solution: def monotoneIncreasingDigits(self, N): """ :type N: int :rtype: int """ a = list(str(N)) i = 1 while i < len(a) and a[i] >= a[i-1]: i += 1 while 0 < i < len(a) and a[i] < a[i-1]: a[i-1] = str(int(a[i-1]) - 1) i -= 1 a[i+1:] = '9' * (len(a)-i-1) return int(''.join(a))
Given a non-negative integer N, find the largest number that is less than or equal to N with monotone increasing digits. (Recall that an integer has monotone increasing digits if and only if each pair of adjacent digits x and y satisfy x .) Example 1: Input: N = 10 Output: 9 Example 2: Input: N = 1234 Output: 1234 Example 3: Input: N = 332 Output: 299 Note: N is an integer in the range [0, 10^9].
class Solution: def monotoneIncreasingDigits(self, N): """ :type N: int :rtype: int """ n, pos = str(N), 0 for i, char in enumerate(n): if i>0 and int(n[i])<int(n[i-1]): return int("".join(n[:pos])+str(int(n[pos])-1)+"9"*(len(n)-1-pos)) if int(n[pos])>1 else int("9"*(len(n)-1-pos)) elif i>0 and n[i] != n[i-1]: pos = i return N
Given a non-negative integer N, find the largest number that is less than or equal to N with monotone increasing digits. (Recall that an integer has monotone increasing digits if and only if each pair of adjacent digits x and y satisfy x .) Example 1: Input: N = 10 Output: 9 Example 2: Input: N = 1234 Output: 1234 Example 3: Input: N = 332 Output: 299 Note: N is an integer in the range [0, 10^9].
class Solution: def monotoneIncreasingDigits(self, N): N = str(N) L = len(N) for i in range(L - 1): if N[i] > N[i + 1]: return self.monotoneIncreasingDigits(int(N[:i] + str(int(N[i]) - 1) + '9' * (L - i - 1))) return int(N)
There are N children standing in a line. Each child is assigned a rating value. You are giving candies to these children subjected to the following requirements: Each child must have at least one candy. Children with a higher rating get more candies than their neighbors. What is the minimum candies you must give? Example 1: Input: [1,0,2] Output: 5 Explanation: You can allocate to the first, second and third child with 2, 1, 2 candies respectively. Example 2: Input: [1,2,2] Output: 4 Explanation: You can allocate to the first, second and third child with 1, 2, 1 candies respectively. The third child gets 1 candy because it satisfies the above two conditions.
class Solution: def candy(self, ratings): """ :type ratings: List[int] :rtype: int """ if not ratings: return 0 total, pre, decrease = 1, 1, 0 for i in range(1, len(ratings)): if ratings[i] >= ratings[i-1]: if decrease > 0: total += (1+decrease)*decrease // 2 if pre <= decrease: total += decrease+1-pre decrease, pre = 0, 1 if ratings[i] == ratings[i-1]: total += 1 pre = 1 else: pre += 1 total += pre else: decrease += 1 if decrease > 0: total += (1 + decrease) * decrease // 2 if pre <= decrease: total += decrease + 1 - pre return total
There are N children standing in a line. Each child is assigned a rating value. You are giving candies to these children subjected to the following requirements: Each child must have at least one candy. Children with a higher rating get more candies than their neighbors. What is the minimum candies you must give? Example 1: Input: [1,0,2] Output: 5 Explanation: You can allocate to the first, second and third child with 2, 1, 2 candies respectively. Example 2: Input: [1,2,2] Output: 4 Explanation: You can allocate to the first, second and third child with 1, 2, 1 candies respectively. The third child gets 1 candy because it satisfies the above two conditions.
class Solution: def candy(self, ratings): """ :type ratings: List[int] :rtype: int """ current_min = 1 current_max = 1 desc_len = 1 cnt = 1 for i in range(1, len(ratings)): if ratings[i] < ratings[i - 1]: if current_min == 1: if desc_len >= current_max: cnt += desc_len + 1 else: cnt += desc_len else: current_max = current_min current_min = 1 cnt += 1 desc_len += 1 elif ratings[i] > ratings[i - 1]: current_min += 1 current_max = current_min cnt += current_min desc_len = 1 else: cnt += 1 current_min = 1 current_max = 1 desc_len = 1 return cnt
There are N children standing in a line. Each child is assigned a rating value. You are giving candies to these children subjected to the following requirements: Each child must have at least one candy. Children with a higher rating get more candies than their neighbors. What is the minimum candies you must give? Example 1: Input: [1,0,2] Output: 5 Explanation: You can allocate to the first, second and third child with 2, 1, 2 candies respectively. Example 2: Input: [1,2,2] Output: 4 Explanation: You can allocate to the first, second and third child with 1, 2, 1 candies respectively. The third child gets 1 candy because it satisfies the above two conditions.
class Solution: def candy(self, ratings): """ :type ratings: List[int] :rtype: int """ current_min = 1 current_max = 1 desc_len = 1 cnt = 1 for i in range(1, len(ratings)): if ratings[i] < ratings[i - 1]: if current_min == 1: cnt += desc_len if desc_len < current_max: cnt -= 1 else: current_max = current_min current_min = 1 desc_len += 1 elif ratings[i] > ratings[i - 1]: current_min += 1 current_max = current_min cnt += current_min - 1 desc_len = 1 else: current_min = 1 current_max = 1 desc_len = 1 cnt += 1 return cnt
There are N children standing in a line. Each child is assigned a rating value. You are giving candies to these children subjected to the following requirements: Each child must have at least one candy. Children with a higher rating get more candies than their neighbors. What is the minimum candies you must give? Example 1: Input: [1,0,2] Output: 5 Explanation: You can allocate to the first, second and third child with 2, 1, 2 candies respectively. Example 2: Input: [1,2,2] Output: 4 Explanation: You can allocate to the first, second and third child with 1, 2, 1 candies respectively. The third child gets 1 candy because it satisfies the above two conditions.
class Solution: def candy(self, ratings): """ :type ratings: List[int] :rtype: int """ n = len(ratings) result = [1] * n for i in range(n-1): if ratings[i+1]> ratings[i]: result[i+1] = result[i] + 1 for i in range(n-1,0,-1): if ratings[i-1] > ratings[i]: result[i-1] = max(result[i]+1, result[i-1]) return sum(result)
There are N children standing in a line. Each child is assigned a rating value. You are giving candies to these children subjected to the following requirements: Each child must have at least one candy. Children with a higher rating get more candies than their neighbors. What is the minimum candies you must give? Example 1: Input: [1,0,2] Output: 5 Explanation: You can allocate to the first, second and third child with 2, 1, 2 candies respectively. Example 2: Input: [1,2,2] Output: 4 Explanation: You can allocate to the first, second and third child with 1, 2, 1 candies respectively. The third child gets 1 candy because it satisfies the above two conditions.
class Solution: def candy(self, ratings): """ :type ratings: List[int] :rtype: int """ candy = [1 for i in range(len(ratings))] for i in range(1, len(ratings)): if ratings[i] > ratings[i - 1]: candy[i] = candy[i - 1] + 1 for i in range(len(ratings) -1)[::-1]: if ratings[i] > ratings[i + 1]: candy[i] = max(candy[i], candy[i + 1] + 1) return sum(candy)
There are N children standing in a line. Each child is assigned a rating value. You are giving candies to these children subjected to the following requirements: Each child must have at least one candy. Children with a higher rating get more candies than their neighbors. What is the minimum candies you must give? Example 1: Input: [1,0,2] Output: 5 Explanation: You can allocate to the first, second and third child with 2, 1, 2 candies respectively. Example 2: Input: [1,2,2] Output: 4 Explanation: You can allocate to the first, second and third child with 1, 2, 1 candies respectively. The third child gets 1 candy because it satisfies the above two conditions.
class Solution: def candy(self, ratings): """ :type ratings: List[int] :rtype: int """ if not ratings: return 0 if len(ratings) == 1: return 1 l2r = [1 for _ in ratings] for i in range(1, len(ratings)): if ratings[i] > ratings[i - 1]: l2r[i] = l2r[i - 1] + 1 res = l2r[-1] for i in range(len(ratings) - 2, -1, -1): if ratings[i] > ratings[i + 1]: l2r[i] = max(l2r[i], l2r[i + 1] + 1) res += l2r[i] return res
There are N children standing in a line. Each child is assigned a rating value. You are giving candies to these children subjected to the following requirements: Each child must have at least one candy. Children with a higher rating get more candies than their neighbors. What is the minimum candies you must give? Example 1: Input: [1,0,2] Output: 5 Explanation: You can allocate to the first, second and third child with 2, 1, 2 candies respectively. Example 2: Input: [1,2,2] Output: 4 Explanation: You can allocate to the first, second and third child with 1, 2, 1 candies respectively. The third child gets 1 candy because it satisfies the above two conditions.
class Solution: def candy(self, ratings): """ :type ratings: List[int] :rtype: int """ if not ratings: return 0 if len(ratings) == 1: return 1 l2r = [1 for _ in ratings] r2l = [1 for _ in ratings] for i in range(1, len(ratings)): if ratings[i] > ratings[i - 1]: l2r[i] = l2r[i - 1] + 1 for i in range(len(ratings) - 2, -1, -1): if ratings[i] > ratings[i + 1]: r2l[i] = r2l[i + 1] + 1 res = 0 for i in range(len(ratings)): res += max(l2r[i], r2l[i]) return res
There are N children standing in a line. Each child is assigned a rating value. You are giving candies to these children subjected to the following requirements: Each child must have at least one candy. Children with a higher rating get more candies than their neighbors. What is the minimum candies you must give? Example 1: Input: [1,0,2] Output: 5 Explanation: You can allocate to the first, second and third child with 2, 1, 2 candies respectively. Example 2: Input: [1,2,2] Output: 4 Explanation: You can allocate to the first, second and third child with 1, 2, 1 candies respectively. The third child gets 1 candy because it satisfies the above two conditions.
class Solution: def candy(self, ratings): """ :type ratings: List[int] :rtype: int """ candies = [0] * len(ratings) from_left = [1] * len(ratings) cur_less_than = 1 for idx in range(1, len(ratings)): if ratings[idx-1] < ratings[idx]: cur_less_than += 1 else: cur_less_than = 1 from_left[idx] = cur_less_than from_right = [1] * len(ratings) cur_less_than = 1 idx = len(ratings)-2 while idx >= 0: if ratings[idx+1] < ratings[idx]: cur_less_than += 1 else: cur_less_than = 1 from_right[idx] = cur_less_than idx -= 1 for idx in range(0, len(ratings)): candies[idx] = max(from_left[idx], from_right[idx]) return sum(candies)
There are N children standing in a line. Each child is assigned a rating value. You are giving candies to these children subjected to the following requirements: Each child must have at least one candy. Children with a higher rating get more candies than their neighbors. What is the minimum candies you must give? Example 1: Input: [1,0,2] Output: 5 Explanation: You can allocate to the first, second and third child with 2, 1, 2 candies respectively. Example 2: Input: [1,2,2] Output: 4 Explanation: You can allocate to the first, second and third child with 1, 2, 1 candies respectively. The third child gets 1 candy because it satisfies the above two conditions.
class Solution: def candy(self, ratings): """ :type ratings: List[int] :rtype: int """ candies = [0] * len(ratings) # min candies at idx i = max of # 1) (number of decreasing ratings to the left) + 1 # 2) (number of decreasing ratings to the right) + 1 # By definition number after end of decreasing sequence will be greater than the end # => both sides of end of decreasing sequence will be greater than the rating at the end # => the min number of candies at the end of the decreasing sequence is 1 # => min number of candies at the (end-n) of the decreasing sequence is 1+n from_left = [1] * len(ratings) cur_less_than = 1 for idx in range(1, len(ratings)): if ratings[idx-1] < ratings[idx]: cur_less_than += 1 else: cur_less_than = 1 from_left[idx] = cur_less_than from_right = [1] * len(ratings) cur_less_than = 1 idx = len(ratings)-2 while idx >= 0: if ratings[idx+1] < ratings[idx]: cur_less_than += 1 else: cur_less_than = 1 from_right[idx] = cur_less_than idx -= 1 for idx in range(0, len(ratings)): candies[idx] = max(from_left[idx], from_right[idx]) return sum(candies)
Return the length of the shortest, non-empty, contiguous subarray of A with sum at least K. If there is no non-empty subarray with sum at least K, return -1.   Example 1: Input: A = [1], K = 1 Output: 1 Example 2: Input: A = [1,2], K = 4 Output: -1 Example 3: Input: A = [2,-1,2], K = 3 Output: 3   Note: 1 <= A.length <= 50000 -10 ^ 5 <= A[i] <= 10 ^ 5 1 <= K <= 10 ^ 9
import collections class Solution: def shortestSubarray(self, A: List[int], K: int) -> int: cum_sum = 0 queue = collections.deque([(-1, 0)]) result = len(A) + 1 for i, v in enumerate(A): cum_sum += v if v > 0: # find any matches and remove them, since will never have a better match while queue and cum_sum - queue[0][1] >= K: e = queue.popleft() #print('remove candidate from start:', e) result = min(result, i - e[0]) else: # for negative numbers pop off any greater cum sums, which will never be a better target while queue and cum_sum <= queue[-1][1]: e = queue.pop() #print('remove lesser from end:', e) queue.append((i, cum_sum)) #print(queue) return result if result <= len(A) else -1
Return the length of the shortest, non-empty, contiguous subarray of A with sum at least K. If there is no non-empty subarray with sum at least K, return -1.   Example 1: Input: A = [1], K = 1 Output: 1 Example 2: Input: A = [1,2], K = 4 Output: -1 Example 3: Input: A = [2,-1,2], K = 3 Output: 3   Note: 1 <= A.length <= 50000 -10 ^ 5 <= A[i] <= 10 ^ 5 1 <= K <= 10 ^ 9
# The solution looks good, # also: https://leetcode.com/problems/shortest-subarray-with-sum-at-least-k/discuss/143726/C%2B%2BJavaPython-O(N)-Using-Deque class Solution: def shortestSubarray(self, A: List[int], K: int) -> int: queue = collections.deque([(0, -1)]) prefix_sum = 0 res = float('inf') for i in range(len(A)): prefix_sum += A[i] while queue and queue[-1][0] > prefix_sum: queue.pop() while queue and prefix_sum - queue[0][0] >= K: res = min(res, i - queue[0][1]) queue.popleft() queue.append((prefix_sum, i)) return res if res != float('inf') else -1
Return the length of the shortest, non-empty, contiguous subarray of A with sum at least K. If there is no non-empty subarray with sum at least K, return -1.   Example 1: Input: A = [1], K = 1 Output: 1 Example 2: Input: A = [1,2], K = 4 Output: -1 Example 3: Input: A = [2,-1,2], K = 3 Output: 3   Note: 1 <= A.length <= 50000 -10 ^ 5 <= A[i] <= 10 ^ 5 1 <= K <= 10 ^ 9
import collections class Solution: def shortestSubarray(self, A: List[int], K: int) -> int: cum_sum = 0 queue = collections.deque([(-1, 0)]) result = len(A) + 1 for i, v in enumerate(A): cum_sum += v # find any matches and remove them, since will never have a better match while queue and cum_sum - queue[0][1] >= K: e = queue.popleft() #print('remove candidate from start:', e) result = min(result, i - e[0]) # pop off any greater cum sums, which will never be a better target while queue and cum_sum <= queue[-1][1]: e = queue.pop() #print('remove greater from end:', e) queue.append((i, cum_sum)) #print(queue) return result if result <= len(A) else -1
Return the length of the shortest, non-empty, contiguous subarray of A with sum at least K. If there is no non-empty subarray with sum at least K, return -1.   Example 1: Input: A = [1], K = 1 Output: 1 Example 2: Input: A = [1,2], K = 4 Output: -1 Example 3: Input: A = [2,-1,2], K = 3 Output: 3   Note: 1 <= A.length <= 50000 -10 ^ 5 <= A[i] <= 10 ^ 5 1 <= K <= 10 ^ 9
class Solution: def shortestSubarray(self, A: List[int], K: int) -> int: B = [0] for a in A: B.append(B[-1] + a) print(B) dq = collections.deque() res = float('inf') for i, n in enumerate(B): while dq and B[dq[-1]] >= n: dq.pop() while dq and n - B[dq[0]] >= K: res = min(res, i-dq[0]) dq.popleft() dq.append(i) return -1 if res == float('inf') else res
Return the length of the shortest, non-empty, contiguous subarray of A with sum at least K. If there is no non-empty subarray with sum at least K, return -1.   Example 1: Input: A = [1], K = 1 Output: 1 Example 2: Input: A = [1,2], K = 4 Output: -1 Example 3: Input: A = [2,-1,2], K = 3 Output: 3   Note: 1 <= A.length <= 50000 -10 ^ 5 <= A[i] <= 10 ^ 5 1 <= K <= 10 ^ 9
class Solution: def shortestSubarray(self, A: List[int], K: int) -> int: total = 0 q = deque() q.append([-1, 0]) res = float('inf') for i, v in enumerate(A): total += v #print(q[0]) while q and total - q[0][1] >=K: res = min(res, i - q[0][0]) q.popleft() while q and total < q[-1][1]: q.pop() q.append([i, total]) return res if res != float('inf') else -1
Return the length of the shortest, non-empty, contiguous subarray of A with sum at least K. If there is no non-empty subarray with sum at least K, return -1.   Example 1: Input: A = [1], K = 1 Output: 1 Example 2: Input: A = [1,2], K = 4 Output: -1 Example 3: Input: A = [2,-1,2], K = 3 Output: 3   Note: 1 <= A.length <= 50000 -10 ^ 5 <= A[i] <= 10 ^ 5 1 <= K <= 10 ^ 9
class Solution: def shortestSubarray(self, A: List[int], K: int) -> int: if not A: return -1 dq = deque([[0, 0]]) curr_sum = 0 min_size = len(A) + 1 for i in range(len(A)): curr_sum += A[i] while dq and curr_sum - dq[0][1] >= K: min_size = min(min_size, i - dq.popleft()[0] + 1) while dq and curr_sum <= dq[-1][1]: dq.pop() dq.append([i+1, curr_sum]) return min_size if min_size != len(A) + 1 else -1
Return the length of the shortest, non-empty, contiguous subarray of A with sum at least K. If there is no non-empty subarray with sum at least K, return -1.   Example 1: Input: A = [1], K = 1 Output: 1 Example 2: Input: A = [1,2], K = 4 Output: -1 Example 3: Input: A = [2,-1,2], K = 3 Output: 3   Note: 1 <= A.length <= 50000 -10 ^ 5 <= A[i] <= 10 ^ 5 1 <= K <= 10 ^ 9
class Solution: def shortestSubarray(self, A: List[int], K: int) -> int: profits = [0] for num in A: profits.append(profits[-1] + num) ans = float('inf') q = collections.deque() for i in range(len(profits)): py = profits[i] while q and py - profits[q[0]] >= K: ans = min(ans, i - q[0]) q.popleft() while q and py - profits[q[-1]] <= 0: q.pop() q.append(i) return ans if ans != float('inf') else -1
Return the length of the shortest, non-empty, contiguous subarray of A with sum at least K. If there is no non-empty subarray with sum at least K, return -1.   Example 1: Input: A = [1], K = 1 Output: 1 Example 2: Input: A = [1,2], K = 4 Output: -1 Example 3: Input: A = [2,-1,2], K = 3 Output: 3   Note: 1 <= A.length <= 50000 -10 ^ 5 <= A[i] <= 10 ^ 5 1 <= K <= 10 ^ 9
class Solution: def shortestSubarray(self, A: List[int], K: int) -> int: n = len(A) preSum = [0 for i in range(n+1)] for i in range(1, n+1): preSum[i] = preSum[i-1] + A[i-1] # print(preSum) deque = [] i = 0 ans = n + 1 while i <= n: while deque and preSum[i] - preSum[deque[0]] >= K: ans = min(ans, i-deque[0]) print(ans) deque.pop(0) while deque and preSum[deque[-1]] >= preSum[i]: deque.pop() deque.append(i) i += 1 # print(deque) return ans if ans < n+1 else -1
Return the length of the shortest, non-empty, contiguous subarray of A with sum at least K. If there is no non-empty subarray with sum at least K, return -1.   Example 1: Input: A = [1], K = 1 Output: 1 Example 2: Input: A = [1,2], K = 4 Output: -1 Example 3: Input: A = [2,-1,2], K = 3 Output: 3   Note: 1 <= A.length <= 50000 -10 ^ 5 <= A[i] <= 10 ^ 5 1 <= K <= 10 ^ 9
from collections import deque class Solution: def shortestSubarray(self, A, K): d = collections.deque([[0, 0]]) res, cur = float('inf'), 0 for i, a in enumerate(A): cur += a while d and cur - d[0][1] >= K: res = min(res, i + 1 - d.popleft()[0]) while d and cur <= d[-1][1]: d.pop() d.append([i + 1, cur]) return res if res < float('inf') else -1
Return the length of the shortest, non-empty, contiguous subarray of A with sum at least K. If there is no non-empty subarray with sum at least K, return -1.   Example 1: Input: A = [1], K = 1 Output: 1 Example 2: Input: A = [1,2], K = 4 Output: -1 Example 3: Input: A = [2,-1,2], K = 3 Output: 3   Note: 1 <= A.length <= 50000 -10 ^ 5 <= A[i] <= 10 ^ 5 1 <= K <= 10 ^ 9
from collections import deque class Solution: def shortestSubarray(self, A: List[int], K: int) -> int: if not A: return -1 sum_A = [0] for a in A: sum_A.append(a + sum_A[-1]) d = deque() res = len(A) + 1 for i in range(len(sum_A)): while d and sum_A[i] <= sum_A[d[-1]]: d.pop() while d and sum_A[i] - sum_A[d[0]] >= K: res = min(res, i - d.popleft()) d.append(i) return res if res != len(A) + 1 else -1
Return the length of the shortest, non-empty, contiguous subarray of A with sum at least K. If there is no non-empty subarray with sum at least K, return -1.   Example 1: Input: A = [1], K = 1 Output: 1 Example 2: Input: A = [1,2], K = 4 Output: -1 Example 3: Input: A = [2,-1,2], K = 3 Output: 3   Note: 1 <= A.length <= 50000 -10 ^ 5 <= A[i] <= 10 ^ 5 1 <= K <= 10 ^ 9
class Solution: def shortestSubarray(self, A: List[int], K: int) -> int: L = len(A) min_length = L+1 queue = collections.deque([(0, -1)]) cursum = 0 for i in range(L): cursum += A[i] while queue and cursum-queue[0][0]>=K: prevSum, prevIdx = queue.popleft() min_length = min(min_length, i-prevIdx) while queue and queue[-1][0]>=cursum: queue.pop() queue.append((cursum,i)) return min_length if min_length<=L else -1
Return the length of the shortest, non-empty, contiguous subarray of A with sum at least K. If there is no non-empty subarray with sum at least K, return -1.   Example 1: Input: A = [1], K = 1 Output: 1 Example 2: Input: A = [1,2], K = 4 Output: -1 Example 3: Input: A = [2,-1,2], K = 3 Output: 3   Note: 1 <= A.length <= 50000 -10 ^ 5 <= A[i] <= 10 ^ 5 1 <= K <= 10 ^ 9
class Solution(object): def shortestSubarray(self, A, K): d = collections.deque([[0, 0]]) res, cur = float('inf'), 0 for i, a in enumerate(A): cur += a while d and cur - d[0][1] >= K: res = min(res, i + 1 - d.popleft()[0]) while d and cur <= d[-1][1]: d.pop() d.append([i + 1, cur]) return res if res < float('inf') else -1
Return the length of the shortest, non-empty, contiguous subarray of A with sum at least K. If there is no non-empty subarray with sum at least K, return -1.   Example 1: Input: A = [1], K = 1 Output: 1 Example 2: Input: A = [1,2], K = 4 Output: -1 Example 3: Input: A = [2,-1,2], K = 3 Output: 3   Note: 1 <= A.length <= 50000 -10 ^ 5 <= A[i] <= 10 ^ 5 1 <= K <= 10 ^ 9
class Solution: def shortestSubarray(self, A: List[int], k: int) -> int: # left, right = 0, 0 # _sum = 0 # out = sys.maxsize # while right<len(A): # _sum += A[right] # while left<=right and _sum>=k: # if right-left+1<out: # out = right-left+1 # _sum -= A[left] # left +=1 # right +=1 # return out if out!=sys.maxsize else -1 # Fail example # [84,-37,32,40,95] # 167 prefixSum = [0] for i in range(len(A)): prefixSum.append(prefixSum[-1]+A[i]) q = collections.deque() out = sys.maxsize for i in range(len(prefixSum)): while q and prefixSum[i] - prefixSum[q[0]]>=k: out = min(out, i-q.popleft()) while q and prefixSum[i] <= prefixSum[q[-1]]: q.pop() q.append(i) # q.append(i) return out if out!=sys.maxsize else -1
Return the length of the shortest, non-empty, contiguous subarray of A with sum at least K. If there is no non-empty subarray with sum at least K, return -1.   Example 1: Input: A = [1], K = 1 Output: 1 Example 2: Input: A = [1,2], K = 4 Output: -1 Example 3: Input: A = [2,-1,2], K = 3 Output: 3   Note: 1 <= A.length <= 50000 -10 ^ 5 <= A[i] <= 10 ^ 5 1 <= K <= 10 ^ 9
class Solution: def shortestSubarray(self, A: List[int], K: int) -> int: q = collections.deque() n = len(A) B = [0] * (n + 1) for i in range(n): B[i+1] = A[i] + B[i] res = float('inf') for i in range(n + 1): while q and B[i] < B[q[-1]]: # maintain increasing Manatonic queue q.pop() while q and B[i] - B[q[0]] >= K: # find the nearest previous element with sum at least K res = min(res, i - q.popleft()) q.append(i) return res if res != float('inf') else -1
Return the length of the shortest, non-empty, contiguous subarray of A with sum at least K. If there is no non-empty subarray with sum at least K, return -1.   Example 1: Input: A = [1], K = 1 Output: 1 Example 2: Input: A = [1,2], K = 4 Output: -1 Example 3: Input: A = [2,-1,2], K = 3 Output: 3   Note: 1 <= A.length <= 50000 -10 ^ 5 <= A[i] <= 10 ^ 5 1 <= K <= 10 ^ 9
from typing import List import heapq import math class Solution: def shortestSubarray(self, A: List[int], k: int) -> int: shortest = math.inf sum = 0 #priority queue to store tuples (partial_sum, index_last_element) pq = [] #we iterate over array for counter, value in enumerate(A): sum += value if sum >= k: shortest = counter + 1 if counter < shortest else shortest while pq and sum - pq[0][0] >= k: shortest = counter - pq[0][1] if counter - pq[0][1] < shortest else shortest heapq.heappop(pq) heapq.heappush(pq, (sum, counter)) return shortest if shortest != math.inf else -1
Return the length of the shortest, non-empty, contiguous subarray of A with sum at least K. If there is no non-empty subarray with sum at least K, return -1.   Example 1: Input: A = [1], K = 1 Output: 1 Example 2: Input: A = [1,2], K = 4 Output: -1 Example 3: Input: A = [2,-1,2], K = 3 Output: 3   Note: 1 <= A.length <= 50000 -10 ^ 5 <= A[i] <= 10 ^ 5 1 <= K <= 10 ^ 9
class Solution: def shortestSubarray(self, A: List[int], K: int) -> int: sm = 0 pref = [] mn = sys.maxsize for i in range(len(A)): pref.append(A[i] + sm) sm += A[i] st = [(0, -1)] for i in range(len(A)): while len(st) and pref[i] < st[-1][0] : st.pop() while len(st) and pref[i] - st[0][0] >= K: mn = min(mn, i - st[0][1]) st.pop(0) st.append([pref[i], i]) return mn if mn != sys.maxsize else -1
Return the length of the shortest, non-empty, contiguous subarray of A with sum at least K. If there is no non-empty subarray with sum at least K, return -1.   Example 1: Input: A = [1], K = 1 Output: 1 Example 2: Input: A = [1,2], K = 4 Output: -1 Example 3: Input: A = [2,-1,2], K = 3 Output: 3   Note: 1 <= A.length <= 50000 -10 ^ 5 <= A[i] <= 10 ^ 5 1 <= K <= 10 ^ 9
class Solution: def shortestSubarray(self, A: List[int], k: int) -> int: # d = collections.deque([[0, 0]]) # res, cur = float('inf'), 0 # for i, a in enumerate(A): # cur += a # while d and cur - d[0][1] >= K: # res = min(res, i + 1 - d.popleft()[0]) # while d and cur <= d[-1][1]: # d.pop() # d.append([i + 1, cur]) # return res if res < float('inf') else -1 d = collections.deque([[0,0]]) cur = 0 res = float('inf') for i, a in enumerate(A): cur += a while d and cur - d[0][1] >= k: l = d.popleft()[0] res = min(res, i - (l-1)) while d and cur <= d[-1][1]: d.pop() d.append([i+1, cur]) return res if res < float('inf') else -1
Return the length of the shortest, non-empty, contiguous subarray of A with sum at least K. If there is no non-empty subarray with sum at least K, return -1.   Example 1: Input: A = [1], K = 1 Output: 1 Example 2: Input: A = [1,2], K = 4 Output: -1 Example 3: Input: A = [2,-1,2], K = 3 Output: 3   Note: 1 <= A.length <= 50000 -10 ^ 5 <= A[i] <= 10 ^ 5 1 <= K <= 10 ^ 9
class Solution: def shortestSubarray(self, A: List[int], K: int) -> int: presum = [0] for x in A: if x>=K: return 1 presum.append(presum[-1]+x) q = collections.deque() ans = math.inf for i, x in enumerate(A): while q and presum[i+1]-presum[q[-1]]<=x: q.pop() q.append(i) while q and (presum[i+1]-presum[q[0]]>=K or i+1-q[0]>=ans): ans = min(ans, i+1-q[0]) q.popleft() return ans if ans!=math.inf else -1
Return the length of the shortest, non-empty, contiguous subarray of A with sum at least K. If there is no non-empty subarray with sum at least K, return -1.   Example 1: Input: A = [1], K = 1 Output: 1 Example 2: Input: A = [1,2], K = 4 Output: -1 Example 3: Input: A = [2,-1,2], K = 3 Output: 3   Note: 1 <= A.length <= 50000 -10 ^ 5 <= A[i] <= 10 ^ 5 1 <= K <= 10 ^ 9
from typing import List class Solution: def shortestSubarray(self, arr: List[int], K: int) -> int: pr_arr = [arr[i] for i in range(len(arr))] for i in range(1, len(arr)): pr_arr[i] = pr_arr[i - 1] + arr[i] q = [] q.append((0, -1)) min_window_size = float('inf') for i, val in enumerate(pr_arr): while len(q) > 0 and q[len(q) - 1][0] >= val: q.pop() q.append((val, i)) window_sum = val - q[0][0] while window_sum >= K: min_window_size = min(min_window_size, i - q[0][1]) q.pop(0) if len(q) == 0: break window_sum = val - q[0][0] if min_window_size == float('inf'): return -1 return min_window_size
Return the length of the shortest, non-empty, contiguous subarray of A with sum at least K. If there is no non-empty subarray with sum at least K, return -1.   Example 1: Input: A = [1], K = 1 Output: 1 Example 2: Input: A = [1,2], K = 4 Output: -1 Example 3: Input: A = [2,-1,2], K = 3 Output: 3   Note: 1 <= A.length <= 50000 -10 ^ 5 <= A[i] <= 10 ^ 5 1 <= K <= 10 ^ 9
class Solution: def shortestSubarray(self, A: List[int], K: int) -> int: pref = [0] + [*accumulate(A)] ans = math.inf q = deque() for i, s in enumerate(pref): while q and pref[q[-1]] >= s: q.pop() while q and s - pref[q[0]] >= K: ans = min(i - q[0], ans) q.popleft() q.append(i) return -1 if ans == math.inf else ans # keep smallest prefix sum # current sum - smallest prefix sum >= K # record smallest length # pop it out # 2, 5, 6 # 6 # 8
Return the length of the shortest, non-empty, contiguous subarray of A with sum at least K. If there is no non-empty subarray with sum at least K, return -1.   Example 1: Input: A = [1], K = 1 Output: 1 Example 2: Input: A = [1,2], K = 4 Output: -1 Example 3: Input: A = [2,-1,2], K = 3 Output: 3   Note: 1 <= A.length <= 50000 -10 ^ 5 <= A[i] <= 10 ^ 5 1 <= K <= 10 ^ 9
class Solution: def shortestSubarray(self, A: List[int], K: int) -> int: return shortest_subarray(A, K) def shortest_subarray(A: List[int], K: int) -> int: n = len(A) sums = [0] * (n + 1) for i in range(n): sums[i+1] = sums[i] + A[i] result = n + 1 q = deque() for i, total in enumerate(sums): while q and total < sums[q[-1]]: q.pop() while q and total - sums[q[0]] >= K: result = min(result, i - q.popleft()) q.append(i) return result if result <= n else -1
Return the length of the shortest, non-empty, contiguous subarray of A with sum at least K. If there is no non-empty subarray with sum at least K, return -1.   Example 1: Input: A = [1], K = 1 Output: 1 Example 2: Input: A = [1,2], K = 4 Output: -1 Example 3: Input: A = [2,-1,2], K = 3 Output: 3   Note: 1 <= A.length <= 50000 -10 ^ 5 <= A[i] <= 10 ^ 5 1 <= K <= 10 ^ 9
class Solution: def shortestSubarray(self, A: List[int], K: int) -> int: n = len(A) if n == 1: return -1 if A[0]<K else 1 if any(A) >= K: return 1 s = [0] for i in range(n): s.append(s[-1]+A[i]) print(s) i = 0 deque = [] min_length = n+1 while i<n+1: #print(deque) while len(deque) > 0 and s[deque[-1]]>=s[i]: deque.pop() while len(deque) > 0 and s[i]-s[deque[0]]>=K: k = deque.pop(0) min_length = min(min_length, i - k) deque.append(i) i+=1 return min_length if min_length<n+1 else -1
Return the length of the shortest, non-empty, contiguous subarray of A with sum at least K. If there is no non-empty subarray with sum at least K, return -1.   Example 1: Input: A = [1], K = 1 Output: 1 Example 2: Input: A = [1,2], K = 4 Output: -1 Example 3: Input: A = [2,-1,2], K = 3 Output: 3   Note: 1 <= A.length <= 50000 -10 ^ 5 <= A[i] <= 10 ^ 5 1 <= K <= 10 ^ 9
from collections import deque class Solution: def shortestSubarray(self, A: List[int], K: int) -> int: if not len(A): return -1 A += [0] prefsum = [0] for n in A: prefsum.append(prefsum[-1] + n) ans = len(A) + 1 deq = deque() for i in range(len(A)): while len(deq) and prefsum[i] - prefsum[deq[0]] >= K: ans = min(i - deq[0], ans) deq.popleft() while len(deq) and prefsum[i] <= prefsum[deq[-1]]: deq.pop() deq.append(i) if ans == len(A) + 1: return -1 return ans
Return the length of the shortest, non-empty, contiguous subarray of A with sum at least K. If there is no non-empty subarray with sum at least K, return -1.   Example 1: Input: A = [1], K = 1 Output: 1 Example 2: Input: A = [1,2], K = 4 Output: -1 Example 3: Input: A = [2,-1,2], K = 3 Output: 3   Note: 1 <= A.length <= 50000 -10 ^ 5 <= A[i] <= 10 ^ 5 1 <= K <= 10 ^ 9
class Solution: def shortestSubarray(self, A: List[int], K: int) -> int: l= 0 summ = 0 A.insert(0,0) ln = len(A) for i in range(1,ln): A[i]+=A[i-1] minq = collections.deque([0]) best = float('inf') for r in range(1,ln): while minq and A[r]-A[minq[0]]>=K: best = min(best,r-minq[0]) minq.popleft() while minq and A[minq[-1]]>A[r]: minq.pop() minq.append(r) return best if best!=float('inf') else -1
Return the length of the shortest, non-empty, contiguous subarray of A with sum at least K. If there is no non-empty subarray with sum at least K, return -1.   Example 1: Input: A = [1], K = 1 Output: 1 Example 2: Input: A = [1,2], K = 4 Output: -1 Example 3: Input: A = [2,-1,2], K = 3 Output: 3   Note: 1 <= A.length <= 50000 -10 ^ 5 <= A[i] <= 10 ^ 5 1 <= K <= 10 ^ 9
from collections import deque class Solution: def shortestSubarray(self, A, K): acc = [0] for v in A: acc.append(acc[-1] + v) ans, monoq = float('inf'), deque() for size, curS in enumerate(acc): while monoq and curS < acc[monoq[-1]]: monoq.pop() while monoq and curS - acc[monoq[0]] >= K: ans = min(ans, size - monoq.popleft()) monoq.append(size) return ans if ans != float('inf') else -1
Return the length of the shortest, non-empty, contiguous subarray of A with sum at least K. If there is no non-empty subarray with sum at least K, return -1.   Example 1: Input: A = [1], K = 1 Output: 1 Example 2: Input: A = [1,2], K = 4 Output: -1 Example 3: Input: A = [2,-1,2], K = 3 Output: 3   Note: 1 <= A.length <= 50000 -10 ^ 5 <= A[i] <= 10 ^ 5 1 <= K <= 10 ^ 9
import collections class Solution: def shortestSubarray(self, A: List[int], K: int) -> int: n = len(A) p = [0] for x in A: p.append(p[-1] + x) # print(p) ans = n+1 q = collections.deque() for key,val in enumerate(p): while q and val <= p[q[-1]]: q.pop() while q and val - p[q[0]] >= K: ans = min(ans, key - q.popleft()) q.append(key) # print(q) return ans if ans < n+1 else -1
Return the length of the shortest, non-empty, contiguous subarray of A with sum at least K. If there is no non-empty subarray with sum at least K, return -1.   Example 1: Input: A = [1], K = 1 Output: 1 Example 2: Input: A = [1,2], K = 4 Output: -1 Example 3: Input: A = [2,-1,2], K = 3 Output: 3   Note: 1 <= A.length <= 50000 -10 ^ 5 <= A[i] <= 10 ^ 5 1 <= K <= 10 ^ 9
class Solution: def shortestSubarray(self, A: List[int], K: int) -> int: s = [0] for x in A: s += s[-1] +x, q = [] res = len(A) + 2 for i, val in enumerate(s): while q and val - q[0][0] >= K: res = min(res, i - heapq.heappop(q)[1]) heapq.heappush(q, (val, i)) return res if res < len(A) + 2 else -1
Return the length of the shortest, non-empty, contiguous subarray of A with sum at least K. If there is no non-empty subarray with sum at least K, return -1.   Example 1: Input: A = [1], K = 1 Output: 1 Example 2: Input: A = [1,2], K = 4 Output: -1 Example 3: Input: A = [2,-1,2], K = 3 Output: 3   Note: 1 <= A.length <= 50000 -10 ^ 5 <= A[i] <= 10 ^ 5 1 <= K <= 10 ^ 9
from collections import deque class Solution: def shortestSubarray(self, A: List[int], K: int) -> int: d = deque([(0,0)]) curr = 0 n = len(A) res = n + 1 for r in range(n): curr += A[r] while d and curr - d[0][1] >= K: res = min(res, r - d.popleft()[0] + 1) while d and curr <= d[-1][1]: d.pop() d.append((r + 1, curr)) return res if res != n + 1 else -1
Return the length of the shortest, non-empty, contiguous subarray of A with sum at least K. If there is no non-empty subarray with sum at least K, return -1.   Example 1: Input: A = [1], K = 1 Output: 1 Example 2: Input: A = [1,2], K = 4 Output: -1 Example 3: Input: A = [2,-1,2], K = 3 Output: 3   Note: 1 <= A.length <= 50000 -10 ^ 5 <= A[i] <= 10 ^ 5 1 <= K <= 10 ^ 9
class Solution: def shortestSubarray(self, A: List[int], K: int) -> int: if max(A) >= K: return 1 n = len(A) prefix = [0] * (n+1) for i in range(1, n+1): prefix[i] = prefix[i-1] + A[i-1] res = n+1 dq = deque() for y, py in enumerate(prefix): while dq and prefix[dq[-1]] > py: dq.pop() while dq and py - prefix[dq[0]] >= K: res = min(res, y-dq.popleft()) dq.append(y) return res if res <= n else -1
Return the length of the shortest, non-empty, contiguous subarray of A with sum at least K. If there is no non-empty subarray with sum at least K, return -1.   Example 1: Input: A = [1], K = 1 Output: 1 Example 2: Input: A = [1,2], K = 4 Output: -1 Example 3: Input: A = [2,-1,2], K = 3 Output: 3   Note: 1 <= A.length <= 50000 -10 ^ 5 <= A[i] <= 10 ^ 5 1 <= K <= 10 ^ 9
class Solution: def shortestSubarray(self, A: List[int], K: int) -> int: d = collections.deque([[0, 0]]) res, cur = float('inf'), 0 for i, a in enumerate(A): cur += a while d and cur - d[0][1] >= K: res = min(res, i + 1 - d.popleft()[0]) while d and cur <= d[-1][1]: d.pop() d.append([i + 1, cur]) return res if res < float('inf') else -1
Return the length of the shortest, non-empty, contiguous subarray of A with sum at least K. If there is no non-empty subarray with sum at least K, return -1.   Example 1: Input: A = [1], K = 1 Output: 1 Example 2: Input: A = [1,2], K = 4 Output: -1 Example 3: Input: A = [2,-1,2], K = 3 Output: 3   Note: 1 <= A.length <= 50000 -10 ^ 5 <= A[i] <= 10 ^ 5 1 <= K <= 10 ^ 9
class Solution: def shortestSubarray(self, A: List[int], K: int) -> int: N = len(A) P = [0] for x in A: P.append(P[-1] + x) #Want smallest y-x with Py - Px >= K ans = N+1 # N+1 is impossible monoq = collections.deque() #opt(y) candidates, represented as indices of P for y, Py in enumerate(P): #Want opt(y) = largest x with Px <= Py - K while monoq and Py <= P[monoq[-1]]: monoq.pop() while monoq and Py - P[monoq[0]] >= K: ans = min(ans, y - monoq.popleft()) monoq.append(y) return ans if ans < N+1 else -1
Return the length of the shortest, non-empty, contiguous subarray of A with sum at least K. If there is no non-empty subarray with sum at least K, return -1.   Example 1: Input: A = [1], K = 1 Output: 1 Example 2: Input: A = [1,2], K = 4 Output: -1 Example 3: Input: A = [2,-1,2], K = 3 Output: 3   Note: 1 <= A.length <= 50000 -10 ^ 5 <= A[i] <= 10 ^ 5 1 <= K <= 10 ^ 9
class Solution: def shortestSubarray(self, arr, k): n = len(arr) # build prefix sums pSums = [0] for x in arr: pSums.append(pSums[-1] + x) res = n + 1 q = deque() for y, Py in enumerate(pSums): while q and Py <= pSums[q[-1]]: q.pop() while q and Py - pSums[q[0]] >= k: res = min(res, y - q.popleft()) q.append(y) return res if res < n + 1 else -1
Return the length of the shortest, non-empty, contiguous subarray of A with sum at least K. If there is no non-empty subarray with sum at least K, return -1.   Example 1: Input: A = [1], K = 1 Output: 1 Example 2: Input: A = [1,2], K = 4 Output: -1 Example 3: Input: A = [2,-1,2], K = 3 Output: 3   Note: 1 <= A.length <= 50000 -10 ^ 5 <= A[i] <= 10 ^ 5 1 <= K <= 10 ^ 9
class Solution: def shortestSubarray(self, A: List[int], K: int) -> int: queue = [[0,0]] x = 0 ans = float('inf') for index, val in enumerate(A): x += val while queue and x - queue[0][1] >= K: ans = min(ans, index+1-queue[0][0]) queue.pop(0) while queue and x <= queue[-1][1]: queue.pop() queue.append([index+1, x]) if ans == float('inf'): return -1 return ans
Return the length of the shortest, non-empty, contiguous subarray of A with sum at least K. If there is no non-empty subarray with sum at least K, return -1.   Example 1: Input: A = [1], K = 1 Output: 1 Example 2: Input: A = [1,2], K = 4 Output: -1 Example 3: Input: A = [2,-1,2], K = 3 Output: 3   Note: 1 <= A.length <= 50000 -10 ^ 5 <= A[i] <= 10 ^ 5 1 <= K <= 10 ^ 9
class Solution: def shortestSubarray(self, A: List[int], K: int) -> int: pref = [0] + list(itertools.accumulate(A)) q = deque() ans = math.inf for i, n in enumerate(pref): while q and pref[q[-1]] > n: q.pop() while q and n - pref[q[0]] >= K: ans = min(ans, i - q.popleft()) q.append(i) return -1 if ans == math.inf else ans
Return the length of the shortest, non-empty, contiguous subarray of A with sum at least K. If there is no non-empty subarray with sum at least K, return -1.   Example 1: Input: A = [1], K = 1 Output: 1 Example 2: Input: A = [1,2], K = 4 Output: -1 Example 3: Input: A = [2,-1,2], K = 3 Output: 3   Note: 1 <= A.length <= 50000 -10 ^ 5 <= A[i] <= 10 ^ 5 1 <= K <= 10 ^ 9
class Solution(object): def shortestSubarray(self, A, K): N = len(A) P = [0] for x in A: P.append(P[-1] + x) #Want smallest y-x with Py - Px >= K ans = N+1 # N+1 is impossible monoq = collections.deque() #opt(y) candidates, represented as indices of P for y, Py in enumerate(P): #Want opt(y) = largest x with Px <= Py - K while monoq and Py <= P[monoq[-1]]: monoq.pop() while monoq and Py - P[monoq[0]] >= K: ans = min(ans, y - monoq.popleft()) monoq.append(y) return ans if ans < N+1 else -1
Return the length of the shortest, non-empty, contiguous subarray of A with sum at least K. If there is no non-empty subarray with sum at least K, return -1.   Example 1: Input: A = [1], K = 1 Output: 1 Example 2: Input: A = [1,2], K = 4 Output: -1 Example 3: Input: A = [2,-1,2], K = 3 Output: 3   Note: 1 <= A.length <= 50000 -10 ^ 5 <= A[i] <= 10 ^ 5 1 <= K <= 10 ^ 9
class Solution: def shortestSubarray(self, A: List[int], K: int) -> int: S = [0] res = float('inf') for num in A: S.append(S[-1]+num) q = [] for i, s in enumerate(S): while q and S[q[-1]] >= s: q.pop() while q and S[q[0]] + K <= s: cur_i = q.pop(0) res = min(res, i-cur_i) q.append(i) if res == float('inf'): return -1 else: return res # n = len(A) # dp = [[0]*n for _ in range(n)] # res = float('inf') # for i in range(len(A)): # if i == 0: # dp[0][i] = A[i] # else: # dp[0][i] = dp[0][i-1] + A[i] # if dp[0][i] >= K: # res = min(res, i+1) # for i in range(1,n): # for j in range(i,n): # dp[i][j] = dp[i-1][j] - A[i-1] # if dp[i][j] >= K: # res = min(res, j-i+1) # if res == float('inf'): # return -1 # return res
Return the length of the shortest, non-empty, contiguous subarray of A with sum at least K. If there is no non-empty subarray with sum at least K, return -1.   Example 1: Input: A = [1], K = 1 Output: 1 Example 2: Input: A = [1,2], K = 4 Output: -1 Example 3: Input: A = [2,-1,2], K = 3 Output: 3   Note: 1 <= A.length <= 50000 -10 ^ 5 <= A[i] <= 10 ^ 5 1 <= K <= 10 ^ 9
class Solution: def shortestSubarray(self, A: List[int], K: int) -> int: # Sliding window approach with prefix sums and monotonic queue prefix_sums = [0] prefix_sum = 0 for a in A: prefix_sum += a prefix_sums.append(prefix_sum) # Monotonic queue to hold increasing indices from collections import deque mono_q = deque() min_len = len(A) + 1 # Sliding window for y, Py in enumerate(prefix_sums): # Pop the indices that will break the monotonically increasing characteristic # from the right while mono_q and Py <= prefix_sums[mono_q[-1]]: mono_q.pop() while mono_q and Py - prefix_sums[mono_q[0]] >= K: min_len = min(y - mono_q.popleft(), min_len) mono_q.append(y) return min_len if min_len < len(A) + 1 else -1
Return the length of the shortest, non-empty, contiguous subarray of A with sum at least K. If there is no non-empty subarray with sum at least K, return -1.   Example 1: Input: A = [1], K = 1 Output: 1 Example 2: Input: A = [1,2], K = 4 Output: -1 Example 3: Input: A = [2,-1,2], K = 3 Output: 3   Note: 1 <= A.length <= 50000 -10 ^ 5 <= A[i] <= 10 ^ 5 1 <= K <= 10 ^ 9
class Solution: def shortestSubarray(self, A: List[int], K: int) -> int: s = [0] for x in A: s += s[-1] + x, stack = [] res = len(s) + 1 for i, x in enumerate(s): while stack and x <= s[stack[-1]]: stack.pop() while stack and x - s[stack[0]] >=K: res = min(res, i - stack.pop(0)) stack += i, return res if res < len(s) + 1 else -1
Return the length of the shortest, non-empty, contiguous subarray of A with sum at least K. If there is no non-empty subarray with sum at least K, return -1.   Example 1: Input: A = [1], K = 1 Output: 1 Example 2: Input: A = [1,2], K = 4 Output: -1 Example 3: Input: A = [2,-1,2], K = 3 Output: 3   Note: 1 <= A.length <= 50000 -10 ^ 5 <= A[i] <= 10 ^ 5 1 <= K <= 10 ^ 9
from bisect import bisect_left from itertools import accumulate class Solution: def shortestSubarray(self, A: List[int], K: int) -> int: MAX_L = 10**9 res = Solver(A, K, MAX_L).solve(0, len(A)-1) return res if res < MAX_L else -1 class Solver: def __init__(self, A, K, MAX_L): self.A = A self.K = K self.MAX_L = MAX_L def solve(self, i, j): if i == j: return 1 if self.A[i] >= self.K else self.MAX_L if sum((abs(self.A[v]) for v in range(i, j+1))) < self.K: return self.MAX_L m = (i + j) // 2 return min(self.solve(i,m), self.solve(m+1,j), self.solve_pivot(i,j,m)) def bin_search(self, arr, val, v): if arr[-1] < v: return self.MAX_L return val[bisect_left(arr, v)] def solve_pivot(self, i, j, m): leftv, leftc = self.min_arr(m, i-1, -1) rightv, rightc = self.min_arr(m+1, j+1, 1) ans = self.MAX_L for li in range(len(leftv)): l_v,l_cnt = leftv[li], leftc[li] r_cnt = self.bin_search(rightv, rightc, self.K-l_v) ans = min(ans, l_cnt + r_cnt) return ans def min_arr(self, start, stop, step): resv, resc = [], [] acc = 0 for i in range(start, stop, step): acc += self.A[i] if (not resv) or acc > resv[-1]: resv.append(acc) resc.append(abs(start-i)+1) return resv, resc
Return the length of the shortest, non-empty, contiguous subarray of A with sum at least K. If there is no non-empty subarray with sum at least K, return -1.   Example 1: Input: A = [1], K = 1 Output: 1 Example 2: Input: A = [1,2], K = 4 Output: -1 Example 3: Input: A = [2,-1,2], K = 3 Output: 3   Note: 1 <= A.length <= 50000 -10 ^ 5 <= A[i] <= 10 ^ 5 1 <= K <= 10 ^ 9
from collections import deque class Solution: def shortestSubarray(self, A: List[int], K: int) -> int: q = deque([(0, 0)]) presum, ans = 0, float('inf') for idx, n in enumerate(A): presum += n while q and presum - q[0][1] >= K: ans = min(ans, idx + 1 - q.popleft()[0]) while q and q[-1][1] >= presum: q.pop() q.append((idx + 1, presum)) return ans if ans < float('inf') else -1
Return the length of the shortest, non-empty, contiguous subarray of A with sum at least K. If there is no non-empty subarray with sum at least K, return -1.   Example 1: Input: A = [1], K = 1 Output: 1 Example 2: Input: A = [1,2], K = 4 Output: -1 Example 3: Input: A = [2,-1,2], K = 3 Output: 3   Note: 1 <= A.length <= 50000 -10 ^ 5 <= A[i] <= 10 ^ 5 1 <= K <= 10 ^ 9
class Solution: def shortestSubarray(self, A: List[int], K: int) -> int: psum = 0 total = 0 dq = deque([(0,-1)]) res = float('inf') for i, a in enumerate(A): psum += a # print(dq, i, a, psum) while dq and dq[-1][0]>psum: dq.pop() while dq and psum-dq[0][0]>=K: res = min(res, i-dq.popleft()[1]) # print(dq, res) dq.append((psum, i)) #print(dq) return res if res!=float('inf') else -1
Return the length of the shortest, non-empty, contiguous subarray of A with sum at least K. If there is no non-empty subarray with sum at least K, return -1.   Example 1: Input: A = [1], K = 1 Output: 1 Example 2: Input: A = [1,2], K = 4 Output: -1 Example 3: Input: A = [2,-1,2], K = 3 Output: 3   Note: 1 <= A.length <= 50000 -10 ^ 5 <= A[i] <= 10 ^ 5 1 <= K <= 10 ^ 9
class Solution: def shortestSubarray(self, A: List[int], K: int) -> int: N = len(A) P = [0] for x in A: P.append(P[-1] + x) #append the current sum +=x ans = N + 1 monoq = collections.deque() for y, Py in enumerate(P): while monoq and Py < P[monoq[-1]]: monoq.pop() while monoq and Py - P[monoq[0]] >=K: ans = min(ans, y-monoq.popleft()) monoq.append(y) if ans < N+1: return ans else: return -1 # if not A: # return -1 # sum = 0 # for i in range(len(A)): # sum += A[i] # if sum < K: # i +=1 # elif sum > K: # i -=1 # else: # return i+1 # return -1
Return the length of the shortest, non-empty, contiguous subarray of A with sum at least K. If there is no non-empty subarray with sum at least K, return -1.   Example 1: Input: A = [1], K = 1 Output: 1 Example 2: Input: A = [1,2], K = 4 Output: -1 Example 3: Input: A = [2,-1,2], K = 3 Output: 3   Note: 1 <= A.length <= 50000 -10 ^ 5 <= A[i] <= 10 ^ 5 1 <= K <= 10 ^ 9
class Solution: def shortestSubarray(self, A: List[int], K: int) -> int: pre = [0] n = len(A) for num in A: pre.append(num + pre[-1]) ans = n + 1 stack = deque() # indices of possible start positions for i in range(n + 1): while stack and pre[i] - pre[stack[0]] >= K: ans = min(ans, i - stack.popleft()) while stack and pre[i] <= pre[stack[-1]]: stack.pop() stack.append(i) return ans if ans <= n else -1
Return the length of the shortest, non-empty, contiguous subarray of A with sum at least K. If there is no non-empty subarray with sum at least K, return -1.   Example 1: Input: A = [1], K = 1 Output: 1 Example 2: Input: A = [1,2], K = 4 Output: -1 Example 3: Input: A = [2,-1,2], K = 3 Output: 3   Note: 1 <= A.length <= 50000 -10 ^ 5 <= A[i] <= 10 ^ 5 1 <= K <= 10 ^ 9
class Solution: def shortestSubarray(self, nums: List[int], K: int) -> int: possible_lefts = deque([(0,-1)]) shortest = float('inf') total = 0 for right, num in enumerate(nums): total += num while possible_lefts and total-possible_lefts[0][0] >= K: shortest = min(shortest, right-possible_lefts.popleft()[1]) while possible_lefts and possible_lefts[-1][0] > total: possible_lefts.pop() possible_lefts.append((total, right)) return shortest if shortest != float('inf') else -1
Return the length of the shortest, non-empty, contiguous subarray of A with sum at least K. If there is no non-empty subarray with sum at least K, return -1.   Example 1: Input: A = [1], K = 1 Output: 1 Example 2: Input: A = [1,2], K = 4 Output: -1 Example 3: Input: A = [2,-1,2], K = 3 Output: 3   Note: 1 <= A.length <= 50000 -10 ^ 5 <= A[i] <= 10 ^ 5 1 <= K <= 10 ^ 9
class Solution: def shortestSubarray(self, A: List[int], K: int) -> int: # (index, value) queue = collections.deque([[0, 0]]) res = float('inf') curr = 0 for i, a in enumerate(A): curr += a while queue and curr - queue[0][1] >= K: tmp = queue.popleft() res = min(res, i - tmp[0] + 1) while queue and curr < queue[-1][1]: queue.pop() queue.append([i+1, curr]) return res if res != float('inf') else -1
Return the length of the shortest, non-empty, contiguous subarray of A with sum at least K. If there is no non-empty subarray with sum at least K, return -1.   Example 1: Input: A = [1], K = 1 Output: 1 Example 2: Input: A = [1,2], K = 4 Output: -1 Example 3: Input: A = [2,-1,2], K = 3 Output: 3   Note: 1 <= A.length <= 50000 -10 ^ 5 <= A[i] <= 10 ^ 5 1 <= K <= 10 ^ 9
from bisect import bisect_left from itertools import accumulate class Solution: def shortestSubarray(self, A: List[int], K: int) -> int: MAX_L = 10**9 res = Solver(A, K, MAX_L).solve(0, len(A)-1) return res if res < MAX_L else -1 class Solver: def __init__(self, A, K, MAX_L): self.A = A self.K = K self.MAX_L = MAX_L def solve(self, i, j): if i == j: return 1 if self.A[i] >= self.K else self.MAX_L if sum((abs(self.A[v]) for v in range(i, j+1))) < self.K: return self.MAX_L m = (i + j) // 2 return min([self.solve(i,m), self.solve(m+1,j), self.solve_pivot(i,j,m)]) def bin_search(self, arr, v): if arr[-1][0] < v: return self.MAX_L i = bisect_left(arr, (v, 0)) return arr[i][1] def solve_pivot(self, i, j, m): left = self.min_arr(m, i-1, -1) right = self.min_arr(m+1, j+1, 1) ans = self.MAX_L for l_v, l_cnt in left: r_cnt = self.bin_search(right, self.K-l_v) ans = min(ans, l_cnt + r_cnt) return ans def min_arr(self, start, stop, step): res = [] acc = 0 for i in range(start, stop, step): acc += self.A[i] if (not res) or acc > res[-1][0]: res.append((acc, abs(start-i)+1)) return res
Return the length of the shortest, non-empty, contiguous subarray of A with sum at least K. If there is no non-empty subarray with sum at least K, return -1.   Example 1: Input: A = [1], K = 1 Output: 1 Example 2: Input: A = [1,2], K = 4 Output: -1 Example 3: Input: A = [2,-1,2], K = 3 Output: 3   Note: 1 <= A.length <= 50000 -10 ^ 5 <= A[i] <= 10 ^ 5 1 <= K <= 10 ^ 9
from queue import deque class Solution: def shortestSubarray(self, A: List[int], K: int) -> int: sums=[0] for i in A: sums.append(sums[-1]+i) min_l=len(A)+1 q=deque([]) for i in range(len(sums)): while q and sums[q[-1]]>=sums[i]: q.pop() while q and sums[i]-sums[q[0]]>=K: min_l=min(min_l,i-q.popleft()) q.append(i) if min_l>len(A): return -1 else: return min_l
Return the length of the shortest, non-empty, contiguous subarray of A with sum at least K. If there is no non-empty subarray with sum at least K, return -1.   Example 1: Input: A = [1], K = 1 Output: 1 Example 2: Input: A = [1,2], K = 4 Output: -1 Example 3: Input: A = [2,-1,2], K = 3 Output: 3   Note: 1 <= A.length <= 50000 -10 ^ 5 <= A[i] <= 10 ^ 5 1 <= K <= 10 ^ 9
import collections class Solution: def shortestSubarray(self, A, K): d = collections.deque() cummulative_sum = [0] for a in A: cummulative_sum.append(cummulative_sum[-1] + a) ans = len(cummulative_sum) for idx, x in enumerate(cummulative_sum): while d and x <= cummulative_sum[d[-1]]: d.pop() while d and x - cummulative_sum[d[0]] >= K: ans = min(ans, idx - d[0]) d.popleft() d.append(idx) return ans if ans != len(cummulative_sum) else -1
Return the length of the shortest, non-empty, contiguous subarray of A with sum at least K. If there is no non-empty subarray with sum at least K, return -1.   Example 1: Input: A = [1], K = 1 Output: 1 Example 2: Input: A = [1,2], K = 4 Output: -1 Example 3: Input: A = [2,-1,2], K = 3 Output: 3   Note: 1 <= A.length <= 50000 -10 ^ 5 <= A[i] <= 10 ^ 5 1 <= K <= 10 ^ 9
from heapq import * class Solution: def shortestSubarray(self, A, K): heap, curS, ans = [(0, -1)], 0, float('inf') for i, v in enumerate(A): curS += v while heap and curS - heap[0][0] >= K: ans = min(ans, i - heappop(heap)[1]) heappush(heap, (curS, i)) return ans if ans != float('inf') else -1
Return the length of the shortest, non-empty, contiguous subarray of A with sum at least K. If there is no non-empty subarray with sum at least K, return -1.   Example 1: Input: A = [1], K = 1 Output: 1 Example 2: Input: A = [1,2], K = 4 Output: -1 Example 3: Input: A = [2,-1,2], K = 3 Output: 3   Note: 1 <= A.length <= 50000 -10 ^ 5 <= A[i] <= 10 ^ 5 1 <= K <= 10 ^ 9
class Solution: def shortestSubarray(self, A: List[int], K: int) -> int: prefix = [0] * (len(A)+1) for i in range(len(A)): prefix[i+1] = prefix[i] + A[i] monoq = deque() ans = len(prefix) for i, p in enumerate(prefix): while monoq and prefix[monoq[-1]]>=p: monoq.pop() while monoq and p - prefix[monoq[0]]>=K: ans = min(ans, i-monoq.popleft()) monoq.append(i) return ans if ans<len(prefix) else -1
Return the length of the shortest, non-empty, contiguous subarray of A with sum at least K. If there is no non-empty subarray with sum at least K, return -1.   Example 1: Input: A = [1], K = 1 Output: 1 Example 2: Input: A = [1,2], K = 4 Output: -1 Example 3: Input: A = [2,-1,2], K = 3 Output: 3   Note: 1 <= A.length <= 50000 -10 ^ 5 <= A[i] <= 10 ^ 5 1 <= K <= 10 ^ 9
from bisect import bisect_left from itertools import accumulate class Solution: def shortestSubarray(self, A: List[int], K: int) -> int: MAX_L = 10**9 res = Solver(A, K, MAX_L).solve(0, len(A)-1) return res if res < MAX_L else -1 class Solver: def __init__(self, A, K, MAX_L): self.A = A self.K = K self.MAX_L = MAX_L def solve(self, i, j): if i == j: return 1 if self.A[i] >= self.K else self.MAX_L if sum((abs(self.A[v]) for v in range(i, j+1))) < self.K: return self.MAX_L m = (i + j) // 2 return min(self.solve(i,m), self.solve(m+1,j), self.solve_pivot(i,j,m)) def bin_search(self, arr, v): if arr[-1][0] < v: return self.MAX_L i = bisect_left(arr, (v, 0)) return arr[i][1] def solve_pivot(self, i, j, m): left = self.min_arr(m, i-1, -1) right = self.min_arr(m+1, j+1, 1) ans = self.MAX_L for l_v, l_cnt in left: r_cnt = self.bin_search(right, self.K-l_v) ans = min(ans, l_cnt + r_cnt) return ans def min_arr(self, start, stop, step): res = [] acc = 0 for i in range(start, stop, step): acc += self.A[i] if (not res) or acc > res[-1][0]: res.append((acc, abs(start-i)+1)) return res
Return the length of the shortest, non-empty, contiguous subarray of A with sum at least K. If there is no non-empty subarray with sum at least K, return -1.   Example 1: Input: A = [1], K = 1 Output: 1 Example 2: Input: A = [1,2], K = 4 Output: -1 Example 3: Input: A = [2,-1,2], K = 3 Output: 3   Note: 1 <= A.length <= 50000 -10 ^ 5 <= A[i] <= 10 ^ 5 1 <= K <= 10 ^ 9
import bisect class Solution: def shortestSubarray(self, A: List[int], K: int) -> int: n = len(A) preSums = [0] * (n + 1) for i in range(n): preSums[i + 1] = preSums[i] + A[i] dque = collections.deque() shortest = n + 1 for i in range(n + 1): while dque and preSums[i] - preSums[dque[0]] >= K: shortest = min(shortest, i - dque.popleft()) while dque and preSums[i] <= preSums[dque[-1]]: dque.pop() dque.append(i) return shortest if shortest <= n else -1
Return the length of the shortest, non-empty, contiguous subarray of A with sum at least K. If there is no non-empty subarray with sum at least K, return -1.   Example 1: Input: A = [1], K = 1 Output: 1 Example 2: Input: A = [1,2], K = 4 Output: -1 Example 3: Input: A = [2,-1,2], K = 3 Output: 3   Note: 1 <= A.length <= 50000 -10 ^ 5 <= A[i] <= 10 ^ 5 1 <= K <= 10 ^ 9
class Solution: def shortestSubarray(self, A: List[int], K: int) -> int: presum = [0] for x in A: # if x>=K: return 1, faster without this one presum.append(presum[-1]+x) q = collections.deque() ans = math.inf for i, x in enumerate(A): while q and presum[i+1]-presum[q[-1]]<=x: q.pop() q.append(i) while q and (presum[i+1]-presum[q[0]]>=K):# or i+1-q[0]>=ans: ans = min(ans, i+1-q[0]) q.popleft() return ans if ans!=math.inf else -1
Return the length of the shortest, non-empty, contiguous subarray of A with sum at least K. If there is no non-empty subarray with sum at least K, return -1.   Example 1: Input: A = [1], K = 1 Output: 1 Example 2: Input: A = [1,2], K = 4 Output: -1 Example 3: Input: A = [2,-1,2], K = 3 Output: 3   Note: 1 <= A.length <= 50000 -10 ^ 5 <= A[i] <= 10 ^ 5 1 <= K <= 10 ^ 9
class Solution: def shortestSubarray(self, A: List[int], K: int) -> int: # make p array which is a cumulative sum p=[0] for i in range(len(A)): p.append(p[-1]+A[i]) q=[] result=len(A)+1 # a high value for i in range(len(A)+1): while(q and p[i]-p[q[0]]>=K): result = min( result , i-q[0]) q.pop(0) while(q and p[i]-p[q[-1]]<=0): q.pop() q.append(i) return(-1 if result==len(A)+1 else result)
Return the length of the shortest, non-empty, contiguous subarray of A with sum at least K. If there is no non-empty subarray with sum at least K, return -1.   Example 1: Input: A = [1], K = 1 Output: 1 Example 2: Input: A = [1,2], K = 4 Output: -1 Example 3: Input: A = [2,-1,2], K = 3 Output: 3   Note: 1 <= A.length <= 50000 -10 ^ 5 <= A[i] <= 10 ^ 5 1 <= K <= 10 ^ 9
import collections class Solution: def shortestSubarray(self, A: List[int], K: int) -> int: suma = [0] for item in A: suma.append(suma[-1] + item) ansr = len(A) + 1 queue = collections.deque() for i in range( len(suma)): while queue and suma[i] - suma[queue[0]] >= K: ansr = min(ansr, i-queue[0]) queue.popleft() #shrink the window from left while queue and suma[i] <= suma[queue[-1]]: queue.pop() queue.append(i) if ansr == len(A) + 1: return -1 else: return ansr
Return the length of the shortest, non-empty, contiguous subarray of A with sum at least K. If there is no non-empty subarray with sum at least K, return -1.   Example 1: Input: A = [1], K = 1 Output: 1 Example 2: Input: A = [1,2], K = 4 Output: -1 Example 3: Input: A = [2,-1,2], K = 3 Output: 3   Note: 1 <= A.length <= 50000 -10 ^ 5 <= A[i] <= 10 ^ 5 1 <= K <= 10 ^ 9
from collections import deque class Solution: def shortestSubarray(self, A: List[int], K: int) -> int: rs = [0] for n in A: rs.append(rs[-1]+n) print(rs) q = deque() mn = float('inf') for i,s in enumerate(rs): while q and s <= rs[q[-1]]: q.pop() while q and s-rs[q[0]] >= K: mn = min(mn,i-q.popleft()) q.append(i) return mn if mn != float('inf') else -1
Return the length of the shortest, non-empty, contiguous subarray of A with sum at least K. If there is no non-empty subarray with sum at least K, return -1.   Example 1: Input: A = [1], K = 1 Output: 1 Example 2: Input: A = [1,2], K = 4 Output: -1 Example 3: Input: A = [2,-1,2], K = 3 Output: 3   Note: 1 <= A.length <= 50000 -10 ^ 5 <= A[i] <= 10 ^ 5 1 <= K <= 10 ^ 9
import collections class Solution: def shortestSubarray(self, A: List[int], K: int) -> int: if not A: return -1 if len(A) == 1: if A[0] >= K: return 1 return -1 increasing_A = [0] for i in A: increasing_A.append(increasing_A[-1]+i) min_length = float('inf') queue = collections.deque() for i,v in enumerate(increasing_A): while queue and v <= increasing_A[queue[-1]]: queue.pop() while queue and v-increasing_A[queue[0]] >= K: min_length = min(min_length, i-queue.popleft()) queue.append(i) if min_length == float('inf'): return -1 return min_length
Return the length of the shortest, non-empty, contiguous subarray of A with sum at least K. If there is no non-empty subarray with sum at least K, return -1.   Example 1: Input: A = [1], K = 1 Output: 1 Example 2: Input: A = [1,2], K = 4 Output: -1 Example 3: Input: A = [2,-1,2], K = 3 Output: 3   Note: 1 <= A.length <= 50000 -10 ^ 5 <= A[i] <= 10 ^ 5 1 <= K <= 10 ^ 9
class Solution(object): def shortestSubarray(self, A, K): N = len(A) P = [0] for x in A: P.append(P[-1] + x) #Want smallest y-x with Py - Px >= K ans = N+1 # N+1 is impossible monoq = collections.deque() #opt(y) candidates, represented as indices of P for y, Py in enumerate(P): #Want opt(y) = largest x with Px <= Py - K while monoq and Py <= P[monoq[-1]]: monoq.pop() while monoq and Py - P[monoq[0]] >= K: ans = min(ans, y - monoq.popleft()) monoq.append(y) return ans if ans < N+1 else -1
Return the length of the shortest, non-empty, contiguous subarray of A with sum at least K. If there is no non-empty subarray with sum at least K, return -1.   Example 1: Input: A = [1], K = 1 Output: 1 Example 2: Input: A = [1,2], K = 4 Output: -1 Example 3: Input: A = [2,-1,2], K = 3 Output: 3   Note: 1 <= A.length <= 50000 -10 ^ 5 <= A[i] <= 10 ^ 5 1 <= K <= 10 ^ 9
class Solution: def shortestSubarray(self, A: List[int], K: int) -> int: preSum = [0] for e in A: preSum.append(preSum[-1] + e) min_len = sys.maxsize #0 2 1 3 7 #0 1 3 7 q = collections.deque([]) for i in range(len(preSum)): while q and preSum[q[-1]] > preSum[i]: q.pop() while q and preSum[i] - K >= preSum[q[0]]: min_len = min(min_len, i-q.popleft()) q.append(i) return min_len if min_len != sys.maxsize else -1
Return the length of the shortest, non-empty, contiguous subarray of A with sum at least K. If there is no non-empty subarray with sum at least K, return -1.   Example 1: Input: A = [1], K = 1 Output: 1 Example 2: Input: A = [1,2], K = 4 Output: -1 Example 3: Input: A = [2,-1,2], K = 3 Output: 3   Note: 1 <= A.length <= 50000 -10 ^ 5 <= A[i] <= 10 ^ 5 1 <= K <= 10 ^ 9
# Prepare # From @Sarmon: # \"What makes this problem hard is that we have negative values. # If you haven't already done the problem with positive integers only, # I highly recommend solving it first\" # Minimum Size Subarray Sum # Explanation # Calculate prefix sum B of list A. # B[j] - B[i] represents the sum of subarray A[i] ~ A[j-1] # Deque d will keep indexes of increasing B[i]. # For every B[i], we will compare B[i] - B[d[0]] with K. # Complexity: # Every index will be pushed exactly once. # Every index will be popped at most once. # Time O(N) # Space O(N) # How to think of such solutions? # Basic idea, for array starting at every A[i], find the shortest one with sum at leat K. # In my solution, for B[i], find the smallest j that B[j] - B[i] >= K. # Keep this in mind for understanding two while loops. # What is the purpose of first while loop? # For the current prefix sum B[i], it covers all subarray ending at A[i-1]. # We want know if there is a subarray, which starts from an index, ends at A[i-1] and has at least sum K. # So we start to compare B[i] with the smallest prefix sum in our deque, which is B[D[0]], hoping that [i] - B[d[0]] >= K. # So if B[i] - B[d[0]] >= K, we can update our result res = min(res, i - d.popleft()). # The while loop helps compare one by one, until this condition isn't valid anymore. # Why we pop left in the first while loop? # This the most tricky part that improve my solution to get only O(N). # D[0] exists in our deque, it means that before B[i], we didn't find a subarray whose sum at least K. # B[i] is the first prefix sum that valid this condition. # In other words, A[D[0]] ~ A[i-1] is the shortest subarray starting at A[D[0]] with sum at least K. # We have already find it for A[D[0]] and it can't be shorter, so we can drop it from our deque. # What is the purpose of second while loop? # To keep B[D[i]] increasing in the deque. # Why keep the deque increase? # If B[i] <= B[d.back()] and moreover we already know that i > d.back(), it means that compared with d.back(), # B[i] can help us make the subarray length shorter and sum bigger. So no need to keep d.back() in our deque. class Solution: def shortestSubarray(self, A, K): d = collections.deque([[0, 0]]) res, cur = float('inf'), 0 for i, a in enumerate(A): cur += a while d and cur - d[0][1] >= K: res = min(res, i + 1 - d.popleft()[0]) while d and cur <= d[-1][1]: d.pop() d.append([i + 1, cur]) return res if res < float('inf') else -1
Return the length of the shortest, non-empty, contiguous subarray of A with sum at least K. If there is no non-empty subarray with sum at least K, return -1.   Example 1: Input: A = [1], K = 1 Output: 1 Example 2: Input: A = [1,2], K = 4 Output: -1 Example 3: Input: A = [2,-1,2], K = 3 Output: 3   Note: 1 <= A.length <= 50000 -10 ^ 5 <= A[i] <= 10 ^ 5 1 <= K <= 10 ^ 9
class Solution: def shortestSubarray(self, A: List[int], K: int) -> int: d = collections.deque([[0, 0]]) res, cur = len(A)+1, 0 for i, a in enumerate(A): cur += a while d and cur - d[0][1] >= K: res = min(res, i + 1 - d.popleft()[0]) while d and cur <= d[-1][1]: # new i make the further subarray length shorter and sum bigger d.pop() d.append([i + 1, cur]) return res if res < len(A)+1 else -1
Return the length of the shortest, non-empty, contiguous subarray of A with sum at least K. If there is no non-empty subarray with sum at least K, return -1.   Example 1: Input: A = [1], K = 1 Output: 1 Example 2: Input: A = [1,2], K = 4 Output: -1 Example 3: Input: A = [2,-1,2], K = 3 Output: 3   Note: 1 <= A.length <= 50000 -10 ^ 5 <= A[i] <= 10 ^ 5 1 <= K <= 10 ^ 9
class Solution: def shortestSubarray(self, A: List[int], K: int) -> int: prefix = [0] * (len(A) + 1) for i in range(len(A)): prefix[i + 1] = prefix[i] + A[i] ans = sys.maxsize deque = collections.deque([]) for i in range(len(A) + 1): while deque and prefix[i] - prefix[deque[0]] >= K: ans = min(ans, i - deque[0]) deque.popleft() while deque and prefix[i] <= prefix[deque[-1]]: deque.pop() deque.append(i) return ans if ans != sys.maxsize else -1
Return the length of the shortest, non-empty, contiguous subarray of A with sum at least K. If there is no non-empty subarray with sum at least K, return -1.   Example 1: Input: A = [1], K = 1 Output: 1 Example 2: Input: A = [1,2], K = 4 Output: -1 Example 3: Input: A = [2,-1,2], K = 3 Output: 3   Note: 1 <= A.length <= 50000 -10 ^ 5 <= A[i] <= 10 ^ 5 1 <= K <= 10 ^ 9
class Solution: def shortestSubarray(self, A: List[int], K: int) -> int: if max(A) >= K: return 1 n = len(A) prefix = [0] + list(itertools.accumulate(A)) res = n+1 dq = deque() for y, py in enumerate(prefix): while dq and prefix[dq[-1]] > py: dq.pop() while dq and py - prefix[dq[0]] >= K: res = min(res, y-dq.popleft()) dq.append(y) return res if res <= n else -1
Return the length of the shortest, non-empty, contiguous subarray of A with sum at least K. If there is no non-empty subarray with sum at least K, return -1.   Example 1: Input: A = [1], K = 1 Output: 1 Example 2: Input: A = [1,2], K = 4 Output: -1 Example 3: Input: A = [2,-1,2], K = 3 Output: 3   Note: 1 <= A.length <= 50000 -10 ^ 5 <= A[i] <= 10 ^ 5 1 <= K <= 10 ^ 9
class Solution(object): def shortestSubarray(self, A, K): n = len(A) pref = [0]*(n+1) for i in range(1, n+1): pref[i] = pref[i-1] + A[i-1] node = deque(); ans = n + 1 for i in range(len(pref)): while node and pref[i] - pref[node[0]] >= K: ans = min(ans, i-node[0]) node.popleft() while node and pref[i] <= pref[node[-1]]: node.pop() node.append(i) return ans if ans < n+1 else -1
Return the length of the shortest, non-empty, contiguous subarray of A with sum at least K. If there is no non-empty subarray with sum at least K, return -1.   Example 1: Input: A = [1], K = 1 Output: 1 Example 2: Input: A = [1,2], K = 4 Output: -1 Example 3: Input: A = [2,-1,2], K = 3 Output: 3   Note: 1 <= A.length <= 50000 -10 ^ 5 <= A[i] <= 10 ^ 5 1 <= K <= 10 ^ 9
class Solution: def shortestSubarray(self, A: List[int], K: int) -> int: ans = len(A) + 1 S = deque() S.append([0, -1]) for i, x in enumerate(A): cur = S[-1][0] + x while S and S[-1][0] >= cur: S.pop() S.append([cur, i]) while S[-1][0] >= S[0][0] + K: ans = min(ans, S[-1][1] - S.popleft()[1]) return ans if ans <= len(A) else -1
Return the length of the shortest, non-empty, contiguous subarray of A with sum at least K. If there is no non-empty subarray with sum at least K, return -1.   Example 1: Input: A = [1], K = 1 Output: 1 Example 2: Input: A = [1,2], K = 4 Output: -1 Example 3: Input: A = [2,-1,2], K = 3 Output: 3   Note: 1 <= A.length <= 50000 -10 ^ 5 <= A[i] <= 10 ^ 5 1 <= K <= 10 ^ 9
class Solution: def shortestSubarray(self, A: List[int], K: int) -> int: d = collections.deque([[0, 0]]) res, cur = float('inf'), 0 for i, a in enumerate(A): cur += a while d and cur - d[0][1] >= K: res = min(res, i + 1 - d.popleft()[0]) while d and cur <= d[-1][1]: d.pop() d.append([i + 1, cur]) return res if res != float('inf') else -1
Return the length of the shortest, non-empty, contiguous subarray of A with sum at least K. If there is no non-empty subarray with sum at least K, return -1.   Example 1: Input: A = [1], K = 1 Output: 1 Example 2: Input: A = [1,2], K = 4 Output: -1 Example 3: Input: A = [2,-1,2], K = 3 Output: 3   Note: 1 <= A.length <= 50000 -10 ^ 5 <= A[i] <= 10 ^ 5 1 <= K <= 10 ^ 9
class Solution(object): def shortestSubarray(self, A, K): n = len(A) d = collections.deque([(A[0],0)]) res = n+1 for i in range(1, n): A[i] += A[i-1] A = [0] + A for i in range(n+1): while d and d[-1][0] > A[i]: d.pop() d.append((A[i], i)) while d and A[i] - d[0][0] >= K: res = min(res, i-d[0][1]) d.popleft() return res if res <= n else -1
Return the length of the shortest, non-empty, contiguous subarray of A with sum at least K. If there is no non-empty subarray with sum at least K, return -1.   Example 1: Input: A = [1], K = 1 Output: 1 Example 2: Input: A = [1,2], K = 4 Output: -1 Example 3: Input: A = [2,-1,2], K = 3 Output: 3   Note: 1 <= A.length <= 50000 -10 ^ 5 <= A[i] <= 10 ^ 5 1 <= K <= 10 ^ 9
from heapq import heappush, heappop def kmin(a,k): cur_sum = 0 h = [(0, -1)] min_ = float('inf') for i in range(0, len(a)): cur_sum +=a[i] while h and h[0][0]<=cur_sum-k: min_ = min(min_, i-h[0][1]) heappop(h) heappush(h, (cur_sum, i)) return min_ if min_ != float('inf') else -1 from collections import deque def ksumalt(a,k): q = deque() q.append((-1, 0)) cur_sum = 0 min_len = float('inf') for i in range(len(a)): cur_sum += a[i] while q and cur_sum - q[0][-1] >=k: min_len = min(min_len, i-q[0][0]) q.popleft() while q and cur_sum <= q[-1][-1]: q.pop() q.append((i, cur_sum)) return -1 if min_len == float('inf') else min_len class Solution: def shortestSubarray(self, A: List[int], K: int) -> int: return ksumalt(A, K)
Return the length of the shortest, non-empty, contiguous subarray of A with sum at least K. If there is no non-empty subarray with sum at least K, return -1.   Example 1: Input: A = [1], K = 1 Output: 1 Example 2: Input: A = [1,2], K = 4 Output: -1 Example 3: Input: A = [2,-1,2], K = 3 Output: 3   Note: 1 <= A.length <= 50000 -10 ^ 5 <= A[i] <= 10 ^ 5 1 <= K <= 10 ^ 9
class Solution: def shortestSubarray(self, A: List[int], K: int) -> int: p,n = [0],len(A) for i in range(n): p.append(p[-1]+A[i]) # p[i] = A[0]+A[1]+...+A[i-1] # p[j]-p[i] = sum(A[i:j]) i,ret = 0,float('inf') q = collections.deque() while i < n+1: while q and p[q[-1]] > p[i]: q.pop() q.append(i) while q and p[q[-1]] - p[q[0]] >= K: ind = q.popleft() ret = min(ret,q[-1]-ind) i += 1 return ret if ret!=float('inf') else -1
Return the length of the shortest, non-empty, contiguous subarray of A with sum at least K. If there is no non-empty subarray with sum at least K, return -1.   Example 1: Input: A = [1], K = 1 Output: 1 Example 2: Input: A = [1,2], K = 4 Output: -1 Example 3: Input: A = [2,-1,2], K = 3 Output: 3   Note: 1 <= A.length <= 50000 -10 ^ 5 <= A[i] <= 10 ^ 5 1 <= K <= 10 ^ 9
class Solution: def shortestSubarray(self, A: List[int], K: int) -> int: n, store = len(A), [0] for x in A: store.append(store[-1] + x) res = n + 1 queue = deque() for i, x in enumerate(store): while queue and x <= store[queue[-1]]: queue.pop() while queue and x - store[queue[0]] >= K: res = min(res, i-queue.popleft()) queue.append(i) return res if res < n + 1 else -1