122. 买卖股票的最佳时机 II
区间内,差值最大,注意并不是最低值和最大值差值就是最大,例如,3,7,1,3,4。差值最大是7-3
解法一
- 若价格一直往下跌,不买入
- 假设第一天买入,若买入后价格往下跌,应该下一天买入
- 若下一天价格往下跌,应该当天卖出
- 若到最后一天,应该清盘,若之前买入卖出,否则维持现状
public int maxProfit(int[] prices) {if (prices == null || prices.length <= 1)return 0;int maxProfit = 0, minPrice = prices[0];for (int i = 1; i < prices.length; i++) {if (prices[i] < minPrice) { // 若价格比之前低,应该买入minPrice = prices[i];} else if (i == prices.length - 1) { // 最后一天,强制清盘if (prices[i] - minPrice > 0) {maxProfit += (prices[i] - minPrice);}} else if (prices[i + 1] < prices[i]) { // 若后一天价格比当前低&&之前已经买入,就应该当天卖出maxProfit += (prices[i] - minPrice);minPrice = prices[i + 1];}System.out.println(String.join(",", String.valueOf(prices[i]), String.valueOf(minPrice), String.valueOf(maxProfit)));}return maxProfit;
}
解法二
贪心算法,若当天价格比前一天高,即可卖出,获取利润,统计结果利润
public int maxProfit(int[] prices) {if (prices == null || prices.length <= 1)return 0;int maxProfit = 0;for (int i = 1; i < prices.length; i++) {maxProfit += Math.max(0, prices[i] - prices[i - 1]);}return maxProfit;
}