Input: n = 5, stockPrice = [1, 5, 3, 7, 8]
Output: 20
Explanation:The subsequence [5, 7, 8] can be chosen. Corresponding chosen days are [1, 3, 4] (considering 0-based indexing). Now,
• stockPrice[3] - stockPrice[1] = 7 - 5 = 2 and 3 - 1 = 2
• stockPrice[4] - stockPrice[3]= 8 - 7 = 1 and 4 - 3 = 1
Thus, the subsequence is balanced. Score= 5 + 7 + 8 = 20
The subsequence [1, 3] can be chosen. Corresponding chosen days are [0, 2] (considering 0-based indexing). Now,
• stockPrice[2] - stockPrice[0] = 3 - 1 = 2 and 2 - 0 = 2
Thus, the subsequence is balanced. Score= 1 + 3 = 4
20 is maximum possible. So, the answer is 20.
Input: n = 3, stockPrice = [1, 2, 3]
Output: 6
Explanation:The subsequence [1, 2, 3] can be chosen. Corresponding chosen days are [0, 1, 2] (considering 0-based indexing). Now,
• stockPrice[1] - stockPrice[0]= 2 - 1= 1 and 1 - 0 = 1
• stockPrice[2] - stockPrice[1]= 3 - 2 = 1 and 2 - 1 = 1
Thus, the subsequence is balanced. Score= 1 + 2 + 3 = 6
6 is maximum possible. So, the answer is 6.
Idea: The given equation can be reformulated as:
• stockPrice[chosenDays[i]] - chosenDays[i] = stockPrice[chosenDays[i-1]] - chosenDays[i-1]
This means that we can group elements together if the difference between their stock price and their index is the same.For example, in the given input 1, the elements 5, 7, and 8 can be grouped together because:
• 5 - 1 = 4
• 7 - 3 = 4
• 8 - 4 = 4
In other words, the solution works by finding the "gaps" between the stock prices. If two stock prices have the same gap, then they can be grouped together in a balanced subsequence. Now the problem is just reduced to storing the sum of elements corresponding to the gap.