Maximum Points You Can Obtain from Cards

MediumSliding Windowsliding window

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

Cards are laid out in a row, and card_points[i] is the value of card i. You take exactly k cards, one at a time, and each time you must take either the leftmost or the rightmost remaining card. Return the maximum total value of the k cards you take.

Examples

Input: card_points = [1,2,3,4,5,6,1], k = 3
Output: 12
Take the three rightmost cards: 1 + 6 + 5 = 12.
Input: card_points = [2,2,2], k = 2
Output: 4
Any two cards total 4.
Input: card_points = [9,7,7,9,7,7,9], k = 7
Output: 55
You must take every card.

Constraints

  • 1 <= card_points.length <= 10^5
  • 1 <= card_points[i] <= 10^4
  • 1 <= k <= card_points.length

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More sliding window problems