|
| 1 | +package solutions; |
| 2 | + |
| 3 | +// [Problem] https://leetcode.com/problems/maximum-points-you-can-obtain-from-cards |
| 4 | +class MaximumPointsFromCards { |
| 5 | + // Sliding window |
| 6 | + // O(k) time, O(1) space |
| 7 | + public int maxScore(int[] cardPoints, int k) { |
| 8 | + int sum = 0; |
| 9 | + int n = cardPoints.length, left = n - k; |
| 10 | + for (int right = left; right < n; right++) { |
| 11 | + sum += cardPoints[right]; |
| 12 | + } |
| 13 | + int maxSum = sum; |
| 14 | + for (int right = 0; right < k; right++) { |
| 15 | + sum -= cardPoints[left++]; |
| 16 | + sum += cardPoints[right]; |
| 17 | + maxSum = Math.max(maxSum, sum); |
| 18 | + } |
| 19 | + return maxSum; |
| 20 | + } |
| 21 | + |
| 22 | + // Test |
| 23 | + public static void main(String[] args) { |
| 24 | + MaximumPointsFromCards solution = new MaximumPointsFromCards(); |
| 25 | + |
| 26 | + int[] input1 = {1, 2, 3, 4, 5, 6, 1}; |
| 27 | + int expectedOutput1 = 12; |
| 28 | + int actualOutput1 = solution.maxScore(input1, 3); |
| 29 | + System.out.println("Test 1 passed? " + (expectedOutput1 == actualOutput1)); |
| 30 | + |
| 31 | + int[] input2 = {9, 7, 7, 9, 7, 7, 9}; |
| 32 | + int expectedOutput2 = 55; |
| 33 | + int actualOutput2 = solution.maxScore(input2, 7); |
| 34 | + System.out.println("Test 2 passed? " + (expectedOutput2 == actualOutput2)); |
| 35 | + } |
| 36 | +} |
0 commit comments