从起点开始k个数的sum记为sum1,从终点开始k个数的sum记为sum2
如果sum1 > sum2,则说明相应长度取左边价值会更大,取完之后sum1 - 当前“起点”,sum2 - 当前“终点”
否则,取右边,sum1 - 当前“终点”,sum2 - 当前“起点”
相等时无所谓
class Solution { public: int maxScore(vector<int>& cardPoints, int k) { int sum1 = 0, sum2 = 0; int p = 0, q = cardPoints.size() - 1; int len = cardPoints.size(); for(int i = 0; i < len && i < k; i++) { sum1 += cardPoints[i]; sum2 += cardPoints[len - i - 1]; } int ret = 0; int k1 = k, k2 = k; while(k) { if(sum1 >= sum2) { ret += cardPoints[p]; sum1 -= cardPoints[p]; sum2 -= cardPoints[len - k2]; k2--; p++; } else { ret += cardPoints[q]; sum2 -= cardPoints[q]; sum1 -= cardPoints[k1 - 1]; k1--; q--; } k--; } return ret; } };