LeetCode 2898: Maximum Linear Stock Score
Problem Description
Explanation:
To solve this problem, we can use dynamic programming with two states: the current day we are at, and whether we currently hold a stock or not. We'll keep track of the maximum possible score we can achieve at each state.
At each day, we can either:
- Buy a stock if we don't hold one already.
- Sell the stock if we hold one.
- Skip the day and do nothing.
The key idea is to transition between these states based on the actions that maximize the score.
Here are the steps for the algorithm:
- Initialize two arrays
hold
andnotHold
each with a size of the number of days, wherehold[i]
represents the maximum score we can achieve on dayi
if we hold a stock, andnotHold[i]
represents the maximum score on dayi
if we don't hold a stock. - Iterate through each day starting from the first day:
- If we are holding a stock on day
i
, we can either continue holding it (do nothing) or sell it. We choose the action that results in a higher score. - If we are not holding a stock on day
i
, we can either buy a stock or do nothing. We choose the action that results in a higher score.
- If we are holding a stock on day
- The answer will be the maximum score between holding a stock on the last day or not holding a stock on the last day.
The time complexity of this algorithm is O(n) where n is the number of days, and the space complexity is also O(n) since we are using two arrays of size n to store the maximum scores.
:
Solutions
class Solution {
public int maxLinearStockScore(int[] prices) {
int n = prices.length;
int[] hold = new int[n];
int[] notHold = new int[n];
hold[0] = -prices[0];
for (int i = 1; i < n; i++) {
hold[i] = Math.max(hold[i - 1], notHold[i - 1] - prices[i]);
notHold[i] = Math.max(notHold[i - 1], hold[i - 1] + prices[i]);
}
return Math.max(hold[n - 1], notHold[n - 1]);
}
}
Loading editor...