Best Time to Buy and Sell Stock II
題目:
Say you have an array for which the?i?th?element is the price of a given stock on day?i.
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
?翻譯:
用一個數組表示股票每天的價格,數組的第i個數表示股票在第i天的價格。交易次數不限,但一次只能交易一支股票,也就是說手上最多只能持有一支股票,求最大收益。
分析:貪心法。從前向后遍歷數組,只要當天的價格高于前一天的價格,就算入收益。所有增量和就是最大利潤
這道題由于可以無限次買入和賣出。我們都知道炒股想掙錢當然是低價買入高價拋出,那么這里我們只需要從第二天開始,如果當前價格比之前價格高,則把差值加入利潤中,因為我們可以昨天買入,今日賣出,若明日價更高的話,還可以今日買入,明日再拋出,明天價錢低了則今天不買,明天再買因為此時明天買后天賣比今天買后天賣賺得多。以此類推,遍歷完整個數組后即可求得最大利潤。
為什么是看明天價格和今天價格,而不是今天買后面幾天再賣。這是因為,如果后天價格比明天高,那么跟今天買明天賣,然后明天又買,后天賣一個意思;如果后天價格比明天低,那么很明顯,明天就該賣出了,這樣利潤大,然后明天不買了,后天再買,賺得多。
代碼:
public class Solution {public int maxProfit(int[] prices) {if(prices==null||prices.length==0)return 0;//所有增量和就是最大利潤int sum=0;for(int i=1;i<prices.length;i++){if(prices[i]>prices[i-1])sum+=prices[i]-prices[i-1];}return sum;} }
?
轉載于:https://www.cnblogs.com/xiaolovewei/p/8029951.html
總結
以上是生活随笔為你收集整理的Best Time to Buy and Sell Stock II的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 蛛后努力值问题
- 下一篇: CentOS 7 下用 firewall