Cute Google Coding Interview Problem: Maximum Points from Cards
This is a commonly asked Google interview question. Can you solve it?
There are several cards arranged in a row, and each card has an associated number of points. The points are given in the integer array
cardPoints
.In one step, you can take one card from the beginning or from the end of the row. You have to take exactly
k
cards.Your score is the sum of the points of the cards you have taken.
Given the integer array
cardPoints
and the integerk
, return the maximum score you can obtain.
Let’s take a look at an example. Say we’re given the array [1,2,3,4,5,6,1]
and we can pick 3 cards. Remember that we have to pick our cards from the *ends* of the list — so the first card we pick can’t be a card in the middle.
What are our choices?
With the blue line, we’ll take the first three cards, which gives us a score of 6.
With the red lines, we’ll take two from the front, then one from the back, which gives us a score of 4.