auto commit
This commit is contained in:
@ -828,6 +828,28 @@ public int maxSubArray(int[] nums) {
|
||||
}
|
||||
```
|
||||
|
||||
**买入和售出股票最大的收益**
|
||||
|
||||
[121. Best Time to Buy and Sell Stock (Easy)](https://leetcode.com/problems/best-time-to-buy-and-sell-stock/description/)
|
||||
|
||||
题目描述:只进行一次交易。
|
||||
|
||||
只要记录前面的最小价格,将这个最小价格作为买入价格,然后将当前的价格作为售出价格,查看当前收益是不是最大收益。
|
||||
|
||||
```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);
|
||||
}
|
||||
return max;
|
||||
}
|
||||
```
|
||||
|
||||
## 二分查找
|
||||
|
||||
**正常实现**
|
||||
@ -3340,27 +3362,6 @@ public int maxProfit(int[] prices, int fee) {
|
||||
}
|
||||
```
|
||||
|
||||
**买入和售出股票最大的收益**
|
||||
|
||||
[121. Best Time to Buy and Sell Stock (Easy)](https://leetcode.com/problems/best-time-to-buy-and-sell-stock/description/)
|
||||
|
||||
题目描述:只进行一次交易。
|
||||
|
||||
只要记录前面的最小价格,将这个最小价格作为买入价格,然后将当前的价格作为售出价格,查看当前收益是不是最大收益。
|
||||
|
||||
```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);
|
||||
}
|
||||
return max;
|
||||
}
|
||||
```
|
||||
|
||||
**只能进行两次的股票交易**
|
||||
|
||||
|
Reference in New Issue
Block a user