2. 买卖股票的最佳时机
买卖股票的最佳时机
[原题链接](初级算法 - LeetBook - 力扣(LeetCode)全球极客挚爱的技术成长平台 (leetcode-cn.com))
简介
给定一个数组 prices ,其中 prices[i] 是一支给定股票第 i 天的价格。设计一个算法来计算你所能获取的最大利润。你可以尽可能地完成更多的交易(多次买卖一支股票)。
注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。
解法
-
思路:起初我们未持有股票。寻找价格局部的极小值,若此时为最后一天,不买入,交易终止,否则买入这支股票,记录当前天数;寻找价格局部极大值,卖出持有股票,记录当前天数。每次买入或卖出后,当前天数加一。循环执行直到当前天数为最后一天。
-
代码:
-
class Solution { public int maxProfit(int[] prices){ int asset = 0; boolean own = false; for (int i = 0; i < prices.length; ) { //若持有股票 if(own){ i = localMax(prices, i); //找到股价最近的极大值点 asset += prices[i]; //卖出 i++; //选下一支股票 } //若未持有股票 if(!own){ i = localMin(prices, i); //找到股价最近的极小值点 if(i == prices.length - 1) return asset; //若极小值为最后一天的股价,不买入,交易终止 asset -= prices[i]; //买入 i++; //选择下一个卖出时机 } own = !own; //持股状况改变 } return asset; } /** * 找极小值,返回下标 * @param prices * @param index * @return */ private int localMin(int[] prices, int index){ if(index == prices.length -1) return index; if (index == prices.length - 2) return prices[index + 1] <= prices[index] ? index + 1 : index; while(prices[index] >= prices[++index]) if(index == prices.length - 1) return index; return index - 1; } /** * 找极大值,返回下标 * @param prices * @param index * @return */ private int localMax(int[] prices, int index){ if(index == prices.length -1) return index; if (index == prices.length - 2) return prices[index + 1] >= prices[index] ? index + 1 : index; while(prices[index] <= prices[++index]) if(index == prices.length - 1) return index; return index - 1; } }
-
-
遍历一次数组,时间复杂度为O(n),结果见下图

浙公网安备 33010602011771号