LeetCode: Maximum Points You Can Obtain From Cards Solution
Approach
11 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}1617// memoized recursion (MLE)18var maxScore = function (cardPoints, k) {19 const N = cardPoints.length20 const memo = Array.from({ length: N }, _ => Array(N).fill(undefined))2122 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 }3435 return recursion(0, cardPoints.length - 1, k)36}
Comments
Loading comments...
Tags
leetcode
array
dynamic programming
sliding window
Apply and earn a $2,500 bonus once you're hired on your first job!
Clients from the Fortune 500 to Silicon Valley startups
Choose your own rate, get paid on time
From hourly, part-time, to full-time positions
Flexible remote working environment
A lot of open JavaScript jobs!!
Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.
Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.