首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >修正滑动窗

修正滑动窗
EN

Stack Overflow用户
提问于 2021-12-22 19:33:20
回答 1查看 51关注 0票数 0

最近,我在一次面试中被问到一个问题,这个问题是数组中k大小的连续和的修改版本。所以问题是这样的:给出数组a中k元素的最大连续和。我们只能从开始或结束选择k元素,或者从开始选择k-1元素,从开始选择1元素,从开始选择k-2元素,从开始选择2元素,从结束选择k-2元素,从结束选择k-2元素。例如:

代码语言:javascript
复制
[5,-2,3,1,2]
k=3

o/p:8

all possible combinations:[5,-2,3],[3,1,2][5,2,1],[-2,5,2]
max sum combinations: [5,2,1], etc

有人能用java解释逻辑吗。

EN

回答 1

Stack Overflow用户

发布于 2021-12-23 08:34:04

这是我一次测试的结果。

代码语言:javascript
复制
Input array   [5, -2, 3, 1, 2]
Window length 3
Current window  [5, -2, 3]
Sum of current window 6
Current window  [-2, 3, 1]
Sum of current window 2
Current window  [3, 1, 2]
Sum of current window 6
Current window  [1, 2, 5]
Sum of current window 8
Current window  [2, 5, -2]
Sum of current window 5
Maximum sum   8

使用环绕滑动窗口,输入数组中的窗口与值完全相同。只要窗口长度小于数组的长度,窗口长度就无关紧要。

“诀窍”是确保数组下标始终小于数组的长度。因此,我们使用余数(%)运算符来确保数组索引始终在0和array.length -1之间;

这是完整的可运行代码。尝试使用不同的数组和不同的窗口长度。

代码语言:javascript
复制
import java.util.Arrays;

public class WrapAroundSlidingWindow {

    public static void main(String[] args) {
        WrapAroundSlidingWindow wasw = new WrapAroundSlidingWindow();
        
        int[] array = { 5, -2, 3, 1, 2 };
        int k = 3;
        System.out.println("Input array   " + Arrays.toString(array));
        System.out.println("Window length " + k);
        System.out.println("Maximum sum   " + wasw.calculateMaximumSum(array, k));
    }
    
    public int calculateMaximumSum(int[] array, int windowLength) {
        int maximumSum = calculateSum(array, 0, windowLength);
        System.out.println("Sum of current window " + maximumSum);
        
        for (int index = 1; index < array.length; index++) {
            int sum = calculateSum(array, index, windowLength);
            System.out.println("Sum of current window " + sum);
            maximumSum = Math.max(maximumSum, sum);
        }
        
        return maximumSum;
    }
    
    private int calculateSum(int[] array, int startIndex, int windowLength) {
        int sum = 0;
        System.out.print("Current window  [");
        
        for (int index = 0; index < windowLength; index++) {
            int jndex = (startIndex + index) % array.length;
            System.out.print(array[jndex]);
            if (index < windowLength - 1) {
                System.out.print(", ");
            }
            sum += array[jndex];
        }
        System.out.println("]");
        
        return sum;
    }

}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70454252

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档