原题
https://leetcode-cn.com/problems/maximum-points-you-can-obtain-from-cards/

思路
滑动窗口变形,依旧是在滑动的过程中找到最大值

题解
package com.leetcode.code;
/**
* @Description:
* @ClassName: Code1423
* @Author: ZK
* @Date: 2021/2/6 17:49
* @Version: 1.0
*/
public class Code1423 {
public static void main(String[] args) {
int[] cardPoints = {1,2,3,4,5,6,1};
System.out.println(maxScore(cardPoints, 3));
}
public static int maxScore(int[] cardPoints, int k) {
int len = cardPoints.length;
int sum = 0;
// 1.先计算出最后k个的总和
for (int i = len-k; i < len; i++) {
sum += cardPoints[i];
}
int max = sum;
// 2.变形窗口开始滑动滑动
for (int i = 0; i < k; i++) {
sum = sum + cardPoints[i] - cardPoints[len-k+i];
max = Math.max(sum, max);
}
return max;
}
}
该博客详细介绍了如何解决LeetCode上的1423题——最大得分。作者使用了滑动窗口的方法,首先计算出最后k个数的总和作为初始最大值,然后通过滑动窗口更新最大值。代码中展示了如何在滑动过程中不断调整窗口,以找到最大可能的得分。
318

被折叠的 条评论
为什么被折叠?



