File tree Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ public int maxProfit (int [] prices ) {
3
+ int n = prices .length ;
4
+ if (n < 2 ) {
5
+ return 0 ;
6
+ }
7
+
8
+ // //贪心算法
9
+ // int res = 0;
10
+ // for (int i=1; i<n; i++) {
11
+ // res += Math.max(prices[i]-prices[i-1], 0);
12
+ // }
13
+ // return res;
14
+
15
+ // // 动态规划,时间复杂度 n,空间复杂度 n
16
+ // int [][] dp = new int [n][2];
17
+ // dp[0][0] = 0;
18
+ // dp[0][1] = -prices[0];
19
+
20
+ // for (int i=1; i<n; i++) {
21
+ // dp[i][0] = Math.max(dp[i-1][0], dp[i-1][1]+prices[i]);
22
+ // dp[i][1] = Math.max(dp[i-1][0]-prices[i], dp[i-1][1]);
23
+ // }
24
+ // return dp[n-1][0];
25
+
26
+ // 动态规划,时间复杂度 n,空间复杂度 1
27
+ int cash = 0 ;
28
+ int hold = 0 ; //赋初值,值无所谓
29
+ int precash = 0 ;
30
+ int prehold = -prices [0 ];
31
+ for (int i =1 ; i <n ; i ++) {
32
+ cash = Math .max (precash , prehold +prices [i ]);
33
+ hold = Math .max (precash -prices [i ], prehold );
34
+ precash = cash ;
35
+ prehold = hold ;
36
+ }
37
+ return cash ;
38
+ }
39
+ }
You can’t perform that action at this time.
0 commit comments