我的思路
妈耶没想到我做出来了。用的是之前那个376. 摆动序列-波峰波谷的思想,只在波谷买入,波峰卖出。
坑就是,这样的for循环没有判断最后一个,我要单独判断最后一天的买卖。
【但AC了就很开心哈哈= =】
var maxProfit = function(prices) {let preDiff =0;let curDiff =0;let owned =false;let result =0;let buyin =0;let soldout =0;for(let i =0;i<prices.length-1;i++){//是波谷且owned为false才买入curDiff =prices[i+1]-prices[i];if(!owned &&(preDiff<=0&&curDiff>0)){buyin =prices[i];owned =!owned;}//是波峰且owned为true才卖出else if(owned &&(preDiff>=0&&curDiff<0)){soldout =prices[i];result+= soldout-buyin;owned =!owned;}console.log(buyin);console.log(soldout);preDiff =curDiff;}if(owned){//最后还持有,卖出let finalResult =prices[prices.length-1] -buyin;if(finalResult>=0){return result+finalResult;}else{return result;}}return result;};
- 时间复杂度:$O(n)$
-
大佬思路
分解利润!
假如第0天买入,第3天卖出,那么利润为:prices[3] - prices[0]。
相当于(prices[3] - prices[2]) + (prices[2] - prices[1]) + (prices[1] - prices[0])。
局部最优:收集每天的正利润,全局最优:求得最大利润。 时间复杂度:$O(n)$
- 空间复杂度:$O(1)$
呜呜呜大佬好聪明啊。代码好短
var maxProfit = function(prices) {let result = 0for(let i = 1; i < prices.length; i++) {result += Math.max(prices[i] - prices[i - 1], 0)}return result};
动态规划
还能动态规划做,见动态规划分组下的解答
