【发布时间】:2020-07-01 05:25:16
【问题描述】:
下面是一个滑动窗口解决方案,用于从 geeksforgeeks (https://www.geeksforgeeks.org/minimum-length-subarray-sum-greater-given-value/) 中找到总和大于 x 的最小长度子数组
# O(n) solution for finding smallest
# subarray with sum greater than x
# Returns length of smallest subarray
# with sum greater than x. If there
# is no subarray with given sum, then
# returns n + 1
def smallestSubWithSum(arr, n, x):
# Initialize current sum and minimum length
curr_sum = 0
min_len = n + 1
# Initialize starting and ending indexes
start = 0
end = 0
while (end < n):
# Keep adding array elements while current
# sum is smaller than x
while (curr_sum <= x and end < n):
curr_sum += arr[end]
end+= 1
# If current sum becomes greater than x.
while (curr_sum > x and start < n):
# Update minimum length if needed
if (end - start < min_len):
min_len = end - start
# remove starting elements
curr_sum -= arr[start]
start+= 1
return min_len
我已经测试过这个解决方案可以工作,但我很困惑为什么在最后一个 while 循环中,检查 start 是否小于 n - 你不希望它小于 end,否则 start 可以去超越终点,这对我来说真的没有意义吗?
【问题讨论】:
标签: python arrays algorithm sliding-window sub-array