mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
Merge pull request #733 from ironartisan/master
添加121.买卖股票的最佳时机.mdJava解法
This commit is contained in:
@ -214,6 +214,26 @@ class Solution {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
```java
|
||||||
|
// 解法1
|
||||||
|
class Solution {
|
||||||
|
public int maxProfit(int[] prices) {
|
||||||
|
if (prices == null || prices.length == 0) return 0;
|
||||||
|
int length = prices.length;
|
||||||
|
// dp[i][0]代表第i天持有股票的最大收益
|
||||||
|
// dp[i][1]代表第i天不持有股票的最大收益
|
||||||
|
int[][] dp = new int[length][2];
|
||||||
|
int result = 0;
|
||||||
|
dp[0][0] = -prices[0];
|
||||||
|
dp[0][1] = 0;
|
||||||
|
for (int i = 1; i < length; i++) {
|
||||||
|
dp[i][0] = Math.max(dp[i - 1][0], -prices[i]);
|
||||||
|
dp[i][1] = Math.max(dp[i - 1][0] + prices[i], dp[i - 1][1]);
|
||||||
|
}
|
||||||
|
return dp[length - 1][1];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
``` java
|
``` java
|
||||||
class Solution { // 动态规划解法
|
class Solution { // 动态规划解法
|
||||||
|
Reference in New Issue
Block a user