1. 买卖股票的最佳时机
(以下均忽略暴力求解)
一次遍历
策略:
既然只有一次交易,那么可以通过遍历来寻找最大的差值
过程:
时间复杂度:O(n)
空间复杂度:O(1)
public class Solution {
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 maxprofit;
}
}
2. 买卖股票的最佳时机 II
贪心算法
策略:
- 隔日上涨:今天买入,明天卖出
- 多日上涨:持有股票到最高点再卖出
- 隔日 / 多日下跌:不交易
时间复杂度:O(n)
空间复杂度:O(1)
class Solution {
public int maxProfit(int[] prices) {
int profit = 0;
for (int i = 1; i < prices.length; i++) {
int tmp = prices[i] - prices[i - 1];
if (tmp > 0) profit += tmp;
}
return profit;
}
}
3. 买卖股票的最佳时机 III
时间复杂度:O(n)
空间复杂度:O(1)
var maxProfit = function(prices) {
const n = prices.length;
let buy1 = -prices[0], buy2 = -prices[0];
let sell1 = 0, sell2 = 0;
for (let i = 1; i < n; i++) {
buy1 = Math.max(buy1, -prices[i]);
sell1 = Math.max(sell1, buy1 + prices[i]);
buy2 = Math.max(buy2, sell1 - prices[i]);
sell2 = Math.max(sell2, buy2 + prices[i]);
}
return sell2;
};
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。