122. Best Time to Buy and Sell Stock II
生活随笔
收集整理的這篇文章主要介紹了
122. Best Time to Buy and Sell Stock II
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一、題目
1、審題
2、分析
給出一個股票的每日價格的數組,可以多次交易,求最大利潤是多大。
?
?二、解答
1、思路:
方法一、
求最大利潤,從后往前看,若以現在的價格賣出,前一天的價格買入的話,即可完成這次交易,并獲得利潤。最終統計所有的利潤即可。
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;}?
方法二、
?、?、先查找從當前位置開始的最小值?min,直到后一個數比?min 大則,記錄此最小數?min。
②、從?min?后查從當前開始的最大數?max,直到碰到比前一個數小的,則記錄此最大值?max。
?、?、max -?min?即為一次獲利交易,繼續向后查找。
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;}?
轉載于:https://www.cnblogs.com/skillking/p/9749684.html
《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀總結
以上是生活随笔為你收集整理的122. Best Time to Buy and Sell Stock II的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: shell脚本一键安装nginx
- 下一篇: vue-11-路由嵌套-参数传递-路由高