【发布时间】:2019-07-07 08:56:53
【问题描述】:
public class Main {
static final int k = 0;
public static void main(String[] args) {
int[] arr = {1, -1, -3, 3, 7, -7, -1, -1, 10, 2};
int startIndex = 0, endIndex = 0, currentSum = 0;
int maxDigitsUsed = Integer.MIN_VALUE;
while(endIndex < arr.length - 1){
currentSum += arr[endIndex];
if (currentSum == k && maxDigitsUsed < endIndex - startIndex) {
maxDigitsUsed = endIndex - startIndex;
} else {
endIndex++;
}
}
// moving the startIndex forward when there is a chance to change the sum to k
while (startIndex <= endIndex) {
currentSum -= arr[startIndex];
if (currentSum == k && maxDigitsUsed < endIndex - startIndex) {
maxDigitsUsed = endIndex - startIndex;
}
startIndex++;
}
}
我的教授使用了一个简单的滑动窗口算法,该算法检查加起来为指定总和 k 的最大连续数字,在本例中 k = 0。
但是,当存在负数时,它似乎不起作用。为什么会这样,我应该如何纠正它?此外,最初的实现应该是一个队列,因此任何基于队列的答案都会非常有帮助!
这个基于数组的实现完全是我的尝试,所以请原谅任何严重的错误。最初的问题只涉及正整数,并使用队列而不是数组。
【问题讨论】:
-
而不是使用滑动窗口。如果存在负数,您需要使用前缀和数组
标签: java queue sliding-window