Maximum Points You Can Obtain from Cards in C++

C++Server Side ProgrammingProgramming

Suppose there are several cards arranged in a row, each card has associated points, and these points are given in the integer array called cardPoints. In one step, we can take one card from the beginning or from the end of the row. We have to take exactly k cards. The final score will be the sum of the points of the cards we have taken. So, if we have integer array cardPoints and the integer k, then find the maximum score we can obtain.

So, if the input is like cardPoints = [1,2,3,4,5,6,1], k = 3, then the output will be 12, as after the initial step, our score will always be 1. Now, choosing the rightmost card first will maximize the total score. The optimal strategy is to take the three cards on the right, giving a final score of 1 + 6 + 5 = 12.

To solve this, we will follow these steps −

• Define two arrays pre1 and prev2 and initialize them with v

• ret := 0

• n := size of v

• for initialize i := 1, when i < n, update (increase i by 1), do −

• pre1[i] := pre1[i] + pre1[i - 1]

• for initialize i := n - 2, when i >= 0, update (decrease i by 1), do −

• pre2[i] := pre2[i] + pre2[i + 1]

• if k >= n, then −

• return pre1[n - 1]

• i := k - 1

• ret := pre1[i]

• (decrease i by 1)

• j := n - 1

• while i >= 0, do −

• ret := maximum of ret and (pre1[i] + pre2[j])

• decrease i and j by 1

• ret := maximum of ret and pre2[n - k]

• return ret

Example

Let us see the following implementation to get better understanding −

Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int maxScore(vector<int>& v, int k) {
vector<int> pre1(v.begin(), v.end());
vector<int> pre2(v.begin(), v.end());
int ret = 0;
int n = v.size();
for (int i = 1; i < n; i++) {
pre1[i] += pre1[i - 1];
}
for (int i = n - 2; i >= 0; i--) {
pre2[i] += pre2[i + 1];
}
if (k >= n) {
return pre1[n - 1];
}
int i = k - 1;
ret = pre1[i];
i--;
int j = n - 1;
while (i >= 0) {
ret = max(ret, pre1[i] + pre2[j]);
i--;
j--;
}
ret = max(ret, pre2[n - k]);
return ret;
}
};
main(){
Solution ob;
vector<int> v = {1,2,3,4,5,6,1};
cout << (ob.maxScore(v, 3));
}

{1,2,3,4,5,6,1}

12