Skip to content

1423. Maximum Points You Can Obtain from Cards 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
 public:
  int maxScore(vector<int>& cardPoints, int k) {
    const int n = cardPoints.size();
    const int sum = accumulate(cardPoints.begin(), cardPoints.end(), 0);
    int windowSum =
        accumulate(cardPoints.begin(), cardPoints.begin() + n - k, 0);
    int ans = sum - windowSum;

    for (int i = 0; i < k; ++i) {
      windowSum -= cardPoints[i];
      windowSum += cardPoints[i + n - k];
      ans = max(ans, sum - windowSum);
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
  public int maxScore(int[] cardPoints, int k) {
    final int n = cardPoints.length;
    final int sum = Arrays.stream(cardPoints).sum();
    int windowSum = 0;
    for (int i = 0; i < n - k; ++i)
      windowSum += cardPoints[i];

    int ans = sum - windowSum;

    for (int i = 0; i < k; ++i) {
      windowSum -= cardPoints[i];
      windowSum += cardPoints[i + n - k];
      ans = Math.max(ans, sum - windowSum);
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution:
  def maxScore(self, cardPoints: list[int], k: int) -> int:
    n = len(cardPoints)
    summ = sum(cardPoints)
    windowSum = sum(cardPoints[:n - k])
    ans = summ - windowSum

    for i in range(k):
      windowSum -= cardPoints[i]
      windowSum += cardPoints[i + n - k]
      ans = max(ans, summ - windowSum)

    return ans