Why is my solution wrong?!
QS Description:
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 integer k, return the maximum score you can obtain.
Example:
Input: cardPoints = [1,2,3,4,5,6,1], k = 3
Output: 12
Explanation: After the first step, your score will always be 1. However, choosing the rightmost card first will maximize your total score. The optimal strategy is to take the three cards on the right, giving a final score of 1 + 6 + 5 = 12.
MY SOLUTION
const maxScore = function (cardPoints: number[], k: number) {
if (k > cardPoints.length || k < 1 || cardPoints.length < 1 || cardPoints.length > 10 ** 5) {
console.log("see constrains again");
return;
}
for (let i = 0; i < cardPoints.length; i++) {
if (cardPoints[i] > 10 ** 4) {
console.log("one of array members is higher than 10**4");
return;
}
}
let arr: number[] = [];
let end = cardPoints.length - 1;
let start = 0;
for (let x = 0; x < k; x++) {
arr.push(Math.max(cardPoints[start], cardPoints[end]));
start++;
end--;
}
return arr.reduce((a, b)=> a+b, 0);
};
When I click Run Code it is accepted as shown in this img
Run Code
When I click Submit it is wrong as shown in this img Submit code
HOw is it wrong answer ??! =>> 1+200+80