leetcode-1423
This week’s daily question, do algorithm, have imagination, enough to fully explore the known conditions.
Topic
https://leetcode-cn.com/problems/maximum-points-you-can-obtain-from-cards/
Solution
Backtracking
This problem can only be taken from the beginning or the end at a time, so the decision-making process can be a binary tree.
We use two pointers to the end of the untraversed team head, respectively, as pointers to the left subtree and the right subtree.
1 | const trackback = (cardPoints, k, count, left, right, result) => { |
Reverse thinking + sliding window
The above solution is a conventional solution, but in fact there is a known condition of this problem that we have not made good use of.
That is, each time you can only take the value from the beginning or the end, that is to say, after completing k values, the rest is continuous.
Then assuming the length of the array is n, after taking k values, there are n-k contiguous arrays left.
We only need to find the minimum value of the consecutive array of n-k to derive the maximum value.
1 | var maxScore = function(cardPoints, k) { |