mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2026-02-02 18:39:09 +08:00
Update
This commit is contained in:
@@ -131,9 +131,9 @@ public:
|
||||
|
||||
一旦想到这里了,很自然就会想到贪心了,即:只收集每天的正利润,最后稳稳的就是最大利润了。
|
||||
|
||||
## 其他语言版本
|
||||
# 其他语言版本
|
||||
|
||||
Java:
|
||||
## Java
|
||||
|
||||
```java
|
||||
// 贪心思路
|
||||
@@ -171,7 +171,7 @@ class Solution { // 动态规划
|
||||
|
||||
|
||||
|
||||
Python:
|
||||
## Python
|
||||
```python
|
||||
class Solution:
|
||||
def maxProfit(self, prices: List[int]) -> int:
|
||||
@@ -181,7 +181,21 @@ class Solution:
|
||||
return result
|
||||
```
|
||||
|
||||
Go:
|
||||
python动态规划
|
||||
```python
|
||||
class Solution:
|
||||
def maxProfit(self, prices: List[int]) -> int:
|
||||
length = len(prices)
|
||||
dp = [[0] * 2 for _ in range(length)]
|
||||
dp[0][0] = -prices[0]
|
||||
dp[0][1] = 0
|
||||
for i in range(1, length):
|
||||
dp[i][0] = max(dp[i-1][0], dp[i-1][1] - prices[i]) #注意这里是和121. 买卖股票的最佳时机唯一不同的地方
|
||||
dp[i][1] = max(dp[i-1][1], dp[i-1][0] + prices[i])
|
||||
return dp[-1][1]
|
||||
```
|
||||
|
||||
## Go
|
||||
```golang
|
||||
//贪心算法
|
||||
func maxProfit(prices []int) int {
|
||||
@@ -217,9 +231,9 @@ func maxProfit(prices []int) int {
|
||||
}
|
||||
```
|
||||
|
||||
Javascript:
|
||||
## Javascript
|
||||
贪心
|
||||
```Javascript
|
||||
// 贪心
|
||||
var maxProfit = function(prices) {
|
||||
let result = 0
|
||||
for(let i = 1; i < prices.length; i++) {
|
||||
@@ -229,7 +243,31 @@ var maxProfit = function(prices) {
|
||||
};
|
||||
```
|
||||
|
||||
C:
|
||||
动态规划
|
||||
```javascript
|
||||
const maxProfit = (prices) => {
|
||||
let dp = Array.from(Array(prices.length), () => Array(2).fill(0));
|
||||
// dp[i][0] 表示第i天持有股票所得现金。
|
||||
// dp[i][1] 表示第i天不持有股票所得最多现金
|
||||
dp[0][0] = 0 - prices[0];
|
||||
dp[0][1] = 0;
|
||||
for(let i = 1; i < prices.length; i++) {
|
||||
// 如果第i天持有股票即dp[i][0], 那么可以由两个状态推出来
|
||||
// 第i-1天就持有股票,那么就保持现状,所得现金就是昨天持有股票的所得现金 即:dp[i - 1][0]
|
||||
// 第i天买入股票,所得现金就是昨天不持有股票的所得现金减去 今天的股票价格 即:dp[i - 1][1] - prices[i]
|
||||
dp[i][0] = Math.max(dp[i-1][0], dp[i-1][1] - prices[i]);
|
||||
|
||||
// 在来看看如果第i天不持有股票即dp[i][1]的情况, 依然可以由两个状态推出来
|
||||
// 第i-1天就不持有股票,那么就保持现状,所得现金就是昨天不持有股票的所得现金 即:dp[i - 1][1]
|
||||
// 第i天卖出股票,所得现金就是按照今天股票佳价格卖出后所得现金即:prices[i] + dp[i - 1][0]
|
||||
dp[i][1] = Math.max(dp[i-1][1], dp[i-1][0] + prices[i]);
|
||||
}
|
||||
|
||||
return dp[prices.length -1][0];
|
||||
};
|
||||
```
|
||||
|
||||
## C
|
||||
```c
|
||||
int maxProfit(int* prices, int pricesSize){
|
||||
int result = 0;
|
||||
|
||||
Reference in New Issue
Block a user