LeetCode刷题20-滑动窗口的最大值

 

 方案一:用例通过率90%以上

复制代码
package exam;

import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;

/**
 * 功能描述
 *
 * @author ASUS
 * @version 1.0
 * @Date 2022/8/7
 */
public class Main02 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        // N的个数
        int N = Integer.parseInt(scanner.nextLine());
        // N个数
        List<Integer> list = Arrays.asList(scanner.nextLine().split(" "))
                .stream()
                .map(Integer::parseInt)
                .collect(Collectors.toList());
        // 窗口长度
        int M = Integer.parseInt(scanner.nextLine());

        // 最大值
        int max = 0;
        for (int i = 0; i < list.size() - M + 1; i++) {
            int tmp = list.get(i);
            int count = 1;
            for (int j = i + 1; j < list.size(); j++) {
                tmp = Math.addExact(tmp, list.get(j));
                count++;
                if (count == M) {
                    max = tmp >= max ? tmp : max;
                    break;
                }
            }
        }
        System.out.println(max);
    }
}
复制代码

 

posted @   chch213  阅读(18)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
· 写一个简单的SQL生成工具
· Manus的开源复刻OpenManus初探
点击右上角即可分享
微信分享提示