122. Best Time to Buy and Sell Stock II
生活随笔
收集整理的這篇文章主要介紹了
122. Best Time to Buy and Sell Stock II
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
一、題目
1、審題
2、分析
給出一個(gè)股票的每日價(jià)格的數(shù)組,可以多次交易,求最大利潤(rùn)是多大。
?
?二、解答
1、思路:
方法一、
求最大利潤(rùn),從后往前看,若以現(xiàn)在的價(jià)格賣出,前一天的價(jià)格買入的話,即可完成這次交易,并獲得利潤(rùn)。最終統(tǒng)計(jì)所有的利潤(rùn)即可。
public int maxProfit11(int[] prices) {int total = 0;for (int i = 1; i < prices.length; i++) {if(prices[i] > prices[i-1])total += prices[i] - prices[i-1]; }return total;}?
方法二、
①、先查找從當(dāng)前位置開始的最小值?min,直到后一個(gè)數(shù)比?min 大則,記錄此最小數(shù)?min。
②、從?min?后查從當(dāng)前開始的最大數(shù)?max,直到碰到比前一個(gè)數(shù)小的,則記錄此最大值?max。
③、max -?min?即為一次獲利交易,繼續(xù)向后查找。
public int maxProfit(int[] prices) {int profit = 0, i = 0;int len = prices.length;while(i < len) {while(i < len -1 && prices[i + 1] <= prices[i])i++;int min = prices[i++];while(i < len -1 && prices[i + 1] >= prices[i])i++;profit += i < len ? prices[i++] - min : 0;}return profit;}?
轉(zhuǎn)載于:https://www.cnblogs.com/skillking/p/9749684.html
《新程序員》:云原生和全面數(shù)字化實(shí)踐50位技術(shù)專家共同創(chuàng)作,文字、視頻、音頻交互閱讀總結(jié)
以上是生活随笔為你收集整理的122. Best Time to Buy and Sell Stock II的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: shell脚本一键安装nginx
- 下一篇: vue-11-路由嵌套-参数传递-路由高