Title Description
Given an unordered array ARR, wherein the elements may be positive or negative, may be 0. Given an integer k, find all of the sub-array cumulative sum arr longest sub-arrays of length less than or equal to k
Claim
The time complexity is O (n), the spatial complexity is O (n)
Examples
Enter a description
The first line of two integers N, k. N represents the length of the array, k is defined in the title of the description has been given
N number of the second integer array row
Output Description
Output represents an integer answer
Example 1
Entry
5 -2
3 -2 -4 0 6
Export
4
Remark
\ (1 \ leq N \ leq 10 ^ 5 \)
$ -10 ^ 9 \ leq k \ leq 10 ^ 9 $
$ -100 \ leq arr_i \ $ leq100
Compare ingenious ideas, and create a two arrays min_sum ind, min_sum [i] to represent a minimal array from the end of the input array until i position and, ind [i] to record the starting position of the array index, note that this is from back to front.
In the solving process, the front to back, the condition is calculated for each position of the subarray maximum
n, k = map(int, input().strip().split(' '))
nums = list(map(int, input().strip().split(' ')))
min_sum = [0]*n
ind = [0]*n
min_sum[-1] = nums[-1]
ind[-1] = n-1
for i in range(n-1)[::-1]:
min_sum[i] = min(min_sum[i+1], 0)+nums[i]
if min_sum[i+1] <= 0:
ind[i] = ind[i+1]
else:
ind[i] = i
#start表示子数组的开始,end表示结束位置后一位,s表示索引从start到end-1的子数组和
start = end = s = 0
res = 0
for start in range(n):
end = max(end, start)
# 对于每个start,end不必重新退回到新的start位置。这是因为start是向右移的,要寻找可能存在满足条件的更大的子数组的话,end只能在原有的end基础上右移,因此end不必要重新回到新的start位置。
while end < n and s+min_sum[end] <= k:
s += min_sum[end]
end = ind[end]+1
res = max(res, end-start) #记录最长的子数组
if end > start: #这里表示nums[start:end] > k,此时需要将start右移。当start移动到end-1时,此时s=0
s -= nums[start]
print(res)
Reference material
https://www.nowcoder.com/questionTerminal/3473e545d6924077a4f7cbc850408ade?f=discussion