# LeetCode: Maximum Points You Can Obtain From Cards Solution

## Approach

`.css-ds3kc{display:table-row;}.css-1t8atru{display:table-cell;opacity:0.5;padding-right:var(--chakra-space-6);-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;text-align:right;}1.css-2qghsv{display:table-cell;}1 2 3 4 5 6 12_ _ _3_ _         _4_         _ _5        _ _ _`

## Implementation

```1/**2 * @param {number[]} cardPoints3 * @param {number} k4 * @return {number}5 */6// sliding window7var maxScore = function (cardPoints, k) {8  const N = cardPoints.length9  let res = (sum = cardPoints.slice(0, k).reduce((acc, el) => acc + el, 0))10  for (let i = 1; i < k + 1; i++) {11    sum += cardPoints[N - i] - cardPoints[k - i]12    res = Math.max(res, sum)13  }14  return res15}16
17// memoized recursion (MLE)18var maxScore = function (cardPoints, k) {19  const N = cardPoints.length20  const memo = Array.from({ length: N }, _ => Array(N).fill(undefined))21
22  const recursion = (i, j, k) => {23    if (i > N - 1 || j < 0 || k === 0) {24      return 025    }26    if (memo[i][j] !== undefined) {27      return memo[i][j]28    }29    return (memo[i][j] = Math.max(30      cardPoints[i] + recursion(i + 1, j, k - 1),31      cardPoints[j] + recursion(i, j - 1, k - 1)32    ))33  }34
35  return recursion(0, cardPoints.length - 1, k)36}```

## Tags

leetcode

array

dynamic programming

sliding window

## Next Post

LeetCode: Range Sum Query 2d Immutable

May 12, 2021

Search Posts