英文原题
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 |
分析
这道题我一开始还想着用动态规划去做,想的太复杂了。其实问题可以归结为左边右边一共选k个数,那么左边选了x个右边就是k-x个,这样只要遍历所有的x就可以得出答案了。
python 代码
1 | class Solution: |