# Halo

A magic place for coding

0%

## Problem

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:

Example 2:

Example 3:

Example 4:

Example 5:

Constraints:

• 1 <= cardPoints.length <= 10^5
• 1 <= cardPoints[i] <= 10^4
• 1 <= k <= cardPoints.length

## Analysis

题目给出一个数组，还有一个数字k代表操作的次数。每次操作只能从最左边或最右边取出一个数，问取出数之和最大是多少。这种题目贪心肯定是行不通的，dp又不太好做，因为取数是两边取，我们不妨转化一下思路，题目要求的是从两边取走k个数字，实际上也就是在数组中间保留长度为n - k连续的一段数字，要求这段数字最小。

这样思考题目一下子变简单了，维护一个滑动窗口，要求里面的值最小。假设数组总和是sum，窗口的和是windowSum，滑动过程中维护result = max(result, sum - windowSum)

无

## Summary

这道题目的难点在于转换思路，从反面去思考，转换后就是一个非常简单的滑动窗口问题。这道题目的分享到这里，感谢你的支持！

Welcome to my other publishing channels