题目

解题思路

  1. 先从一边获取所有卡片;
  2. 逐个替换成另一侧的卡片;
  3. 每次替换后比较大小选择最大值;

代码展示

class Solution {
    public int maxScore(int[] cardPoints, int k) {
        int ans = 0;
        //先全部从左边取值
        for (int i = 0; i < k; i++){
            ans += cardPoints[i];
        }
        int n = cardPoints.length;
        int index = 1;
        int temp = ans;
        while (index <= k){
            //逐个替换成右边值再比较
            temp = temp - cardPoints[k - index] + cardPoints[n - index];
            ans = Math.max(ans, temp);
            index++;
        }
        return ans;
    }
}
12-04 05:53