@@ -195,23 +195,26 @@ public:
195
195
## 其他语言版本
196
196
197
197
Java:
198
+
199
+ > 贪心法:
200
+
198
201
```java
199
- // 贪心思路
200
202
class Solution {
201
203
public int maxProfit(int[ ] prices) {
202
- int minprice = Integer . MAX_VALUE ;
203
- int maxprofit = 0 ;
204
- for (int i = 0 ; i < prices. length; i++ ) {
205
- if (prices[i] < minprice) {
206
- minprice = prices[i];
207
- } else if (prices[i] - minprice > maxprofit) {
208
- maxprofit = prices[i] - minprice;
209
- }
204
+ // 找到一个最小的购入点
205
+ int low = Integer.MAX_VALUE;
206
+ // res不断更新,直到数组循环完毕
207
+ int res = 0;
208
+ for(int i = 0; i < prices.length; i++){
209
+ low = Math.min(prices[ i] , low);
210
+ res = Math.max(prices[ i] - low, res);
210
211
}
211
- return maxprofit ;
212
+ return res ;
212
213
}
213
214
}
214
215
```
216
+ > 动态规划:版本一
217
+
215
218
```java
216
219
// 解法1
217
220
class Solution {
@@ -233,30 +236,27 @@ class Solution {
233
236
}
234
237
```
235
238
236
- ``` java
237
- class Solution { // 动态规划解法
238
- public int maxProfit (int [] prices ) {
239
- // 可交易次数
240
- int k = 1 ;
241
- // [天数][交易次数][是否持有股票]
242
- int [][][] dp = new int [prices. length][k + 1 ][2 ];
243
-
244
- // bad case
245
- dp[0 ][0 ][0 ] = 0 ;
246
- dp[0 ][0 ][1 ] = Integer . MIN_VALUE ;
247
- dp[0 ][1 ][0 ] = Integer . MIN_VALUE ;
248
- dp[0 ][1 ][1 ] = - prices[0 ];
249
-
250
- for (int i = 1 ; i < prices. length; i++ ) {
251
- for (int j = k; j >= 1 ; j-- ) {
252
- // dp公式
253
- dp[i][j][0 ] = Math . max(dp[i - 1 ][j][0 ], dp[i - 1 ][j][1 ] + prices[i]);
254
- dp[i][j][1 ] = Math . max(dp[i - 1 ][j][1 ], dp[i - 1 ][j - 1 ][0 ] - prices[i]);
255
- }
256
- }
239
+ > 动态规划:版本二
257
240
258
- return dp[prices. length - 1 ][k][0 ] > 0 ? dp[prices. length - 1 ][k][0 ] : 0 ;
241
+ ``` java
242
+ class Solution {
243
+ public int maxProfit(int[ ] prices) {
244
+ int[ ] dp = new int[ 2] ;
245
+ dp[ 0] = -prices[ 0] ;
246
+ dp[ 1] = 0;
247
+ // 可以参考斐波那契问题的优化方式
248
+ // dp[ 0] 和 dp[ 1] , 其实是第 0 天的数据
249
+ // 所以我们从 i=1 开始遍历数组,一共有 prices.length 天,
250
+ // 所以是 i<=prices.length
251
+ for (int i = 1; i <= prices.length; i++) {
252
+ int temp = dp[ 0] ;
253
+ // 前一天持有;或当天买入
254
+ dp[ 0] = Math.max(temp, -prices[ i - 1] );
255
+ // 前一天卖出;或当天卖出, 当天要卖出,得前一天持有才行
256
+ dp[ 1] = Math.max(dp[ 1] , temp + prices[ i - 1] );
259
257
}
258
+ return dp[ 1] ;
259
+ }
260
260
}
261
261
```
262
262
0 commit comments