These two questions have been done before, and now they are done again with the idea of dynamic programming, and dp is two-dimensional.
Question 1: 121. Best Time to Buy and Sell Stocks - LeetCode
Given an array prices
whose th i
element prices[i]
represents the price of a given stock on the th i
day.
You can only choose to buy the stock on one day and sell it on a different day in the future . Design an algorithm to calculate the maximum profit you can make.
Returns the maximum profit you can make from this trade. If you can't make any profit, return 0
.
Idea: This question cannot be passed with violence, so you have to use dynamic rules to declare a two-dimensional vector, dp[i][j], where j can only be 0, 1, 0 means buying, and 1 means selling. code show as below:
class Solution {
public:
int maxProfit(vector<int>& prices) {
int len = prices.size();
if(len == 0) return 0;
vector<vector<int>> dp(len,vector<int>(2));
dp[0][0] = -prices[0];
dp[0][1] = 0;
for(int i=1;i<len;i++){
dp[i][0] = max(dp[i-1][0],-prices[i]);
dp[i][1] = max(prices[i]+dp[i-1][0],dp[i-1][1]);
}
return dp[len-1][1];
}
};
Question 2: 122. Best Time to Buy and Sell Stocks II - LeetCode
You are given an array of integers prices
, which prices[i]
represents the price of a certain stock on the first i
day.
On each day, you can decide whether to buy and/or sell stocks. You can hold no more than one share of stock at any one time . You can also buy first and then sell on the same day .
Return the maximum profit you can make .
Idea: This question allows multiple transactions, then dp[j] represents the maximum profit on the jth day, the code is as follows:
class Solution {
public:
int maxProfit(vector<int>& prices) {
int len = prices.size();
vector<int> dp(len,0);
for(int i=1;i<len;i++){
dp[i] +=dp[i-1]+max(0,prices[i]-prices[i-1]);
}
return dp[len-1];
}
};