LeetCode1423. Maximum Points You Can Obtain from Cards

文章目录

一、题目

There are several cards arranged in a row, and each card has an associated number of points. The points are given in the integer array cardPoints.

In one step, you can take one card from the beginning or from the end of the row. You have to take exactly k cards.

Your score is the sum of the points of the cards you have taken.

Given the integer array cardPoints and the integer k, return the maximum score you can obtain.

Example 1:

Input: cardPoints = 1,2,3,4,5,6,1, k = 3

Output: 12

Explanation: After the first step, your score will always be 1. However, choosing the rightmost card first will maximize your total score. The optimal strategy is to take the three cards on the right, giving a final score of 1 + 6 + 5 = 12.

Example 2:

Input: cardPoints = 2,2,2, k = 2

Output: 4

Explanation: Regardless of which two cards you take, your score will always be 4.

Example 3:

Input: cardPoints = 9,7,7,9,7,7,9, k = 7

Output: 55

Explanation: You have to take all the cards. Your score is the sum of points of all cards.

Constraints:

1 <= cardPoints.length <= 105

1 <= cardPointsi <= 104

1 <= k <= cardPoints.length

二、题解

从前或后取k个元素和最大,转换为剩余n-k个连续窗口的元素和最小。利用滑动窗口求解。

注意accumulate函数cardPoints[i] - cardPoints[i-windowSize]的写法。

cpp 复制代码
class Solution {
public:
    int maxScore(vector<int>& cardPoints, int k) {
        int n = cardPoints.size();
        int windowSize = n - k;
        int totalSum = accumulate(cardPoints.begin(),cardPoints.end(),0);
        int sum = accumulate(cardPoints.begin(),cardPoints.begin()+windowSize,0);
        int minSum = sum;
        for(int i = windowSize;i < n;i++){
            sum += cardPoints[i] - cardPoints[i-windowSize];
            minSum = min(minSum,sum);
        }
        return totalSum - minSum;
    }
};
相关推荐
战血石LoveYY8 分钟前
Integer类型超限,导致数据异常
java·算法
会周易的程序员9 分钟前
从零构建多核CPU负载自适应控制系统
linux·c++·笔记·物联网·测试工具
紫金修道18 分钟前
PnP算法介绍(Perspective-n-Point)
算法
程序猿编码34 分钟前
用C++从零开始造一个微型GPT,不借助任何第三方库
开发语言·c++·gpt·模型推理
qz5zwangzihan11 小时前
题解:Atcoder Beginner Contest abc466 F - Many Mod Calculation
c++·题解·优先队列·atcoder·大根堆·abc466·abc466f
froyoisle2 小时前
CSP 真题解析:[CSP-J 2019-T4] 加工零件
c++·算法·bfs·csp-j·算法竞赛·信息学·信奥赛
LuminousCPP2 小时前
C 语言集中实践全记录:顺序表 + 单链表原理实现与通讯录项目实战【附可运行源码】
c语言·开发语言·数据结构·经验分享·笔记
2401_869769592 小时前
内容7 内存管理 1
c++
兰令水2 小时前
hot100【acm版】【2026.7.13打卡-java版本】
java·开发语言·数据结构·算法·leetcode·面试
Tisfy2 小时前
LeetCode 1291.顺次数:打表/枚举
算法·leetcode·题解·枚举·遍历