-
Notifications
You must be signed in to change notification settings - Fork 0
/
122_maxProfit.txt
33 lines (32 loc) · 1.12 KB
/
122_maxProfit.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
//C++
class Solution {
public:
//贪心算法,当前最优解
int maxProfit(vector<int>& prices) {
if(prices.size()==0||prices.size()==1)
return 0;
int maxpro = 0;
for(int i = 0;i < prices.size()-1;i++){
maxpro += (prices[i+1]-prices[i] > 0)?(prices[i+1]-prices[i]):0;
}
return maxpro;
}
};
//java
class Solution {
public int maxProfit(int[] prices) {
//动态规划用dp[i][0]和dp[i][1]分别表示第i天未持有和已持有股票的收益
int n = prices.length;
int[][] dp = new int[n][2];
//初始化第0天的
dp[0][0] = 0;
dp[0][1] = -prices[0];
for(int i = 1;i<n;i++){
//第i天未持有的最大值由前一天未持有与前一天已持有在这一天卖出两者的最大值决定
dp[i][0] = Math.max(dp[i-1][0],dp[i-1][1]+prices[i]);
//第i天已持有的最大值由前一天已持有与前一天未持有在这一天买入两者的最大值决定
dp[i][1] = Math.max(dp[i-1][1],dp[i-1][0]-prices[i]);
}
return dp[n-1][0];
}
}