修复 6. 买卖股票的最大收益 II 的错误
6. 买卖股票的最大收益 II 目前文档中的写法是错误的,不能通过 leetcode。 我提供了一种简单的写法,通过了 leetcode。 希望帮助这个仓库越来越完美
This commit is contained in:
parent
f5ad47b470
commit
1018f055c9
@ -196,17 +196,19 @@ public int[][] reconstructQueue(int[][] people) {
|
||||
只要记录前面的最小价格,将这个最小价格作为买入价格,然后将当前的价格作为售出价格,查看当前收益是不是最大收益。
|
||||
|
||||
```java
|
||||
public int maxProfit(int[] prices) {
|
||||
int n = prices.length;
|
||||
if (n == 0) return 0;
|
||||
int soFarMin = prices[0];
|
||||
int max = 0;
|
||||
for (int i = 1; i < n; i++) {
|
||||
if (soFarMin > prices[i]) soFarMin = prices[i];
|
||||
else max = Math.max(max, prices[i] - soFarMin);
|
||||
public int maxProfit(int prices[]) {
|
||||
int minprice = Integer.MAX_VALUE;
|
||||
int maxprofit = 0;
|
||||
for (int i = 0; i < prices.length; i++) {
|
||||
if (prices[i] < minprice) {
|
||||
minprice = prices[i];
|
||||
} else if (prices[i] - minprice > maxprofit) {
|
||||
maxprofit = prices[i] - minprice;
|
||||
}
|
||||
return max;
|
||||
}
|
||||
return maxprofit;
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
|
||||
|
Loading…
x
Reference in New Issue
Block a user