題目:算法
給定一個數組,它的第 i 個元素是一支給定股票第 i 天的價格。數組
設計一個算法來計算你所能獲取的最大利潤。你能夠儘量地完成更多的交易(屢次買賣一支股票)。spa
注意:你不能同時參與多筆交易(你必須在再次購買前出售掉以前的股票)。設計
思路:code
採用貪心算法,若是當天股票的價格 pi 大於等於前一天的股票價格 pi-1 則持續持有。若是低於前一天的價格,則在前一天就拋售股票。
blog
時間複雜度:O(N)。從頭遍歷每一天的股票價格。it
空間複雜度:O(1)。io
class Solution { public: int maxProfit(vector<int>& prices) { int buyin = 0, keep = 1, profit = 0; int len = prices.size(); while(buyin+keep < len) { int buyP = prices[buyin]; for(keep; keep < (len-buyin); keep++) { if(prices[buyin+keep-1] > prices[buyin+keep]) { if(keep > 1) { profit = profit + (prices[buyin+keep-1] - buyP); } break; } else { if(buyin+keep+1 == len) profit = profit + (prices[buyin+keep] - buyP); } } buyin = buyin+keep; keep = 1; } return profit; } };
另外一種思路。每一天都盯盤,只要當天利潤P>0,買賣股票,利潤增長。若是當天利潤P≤0,不進行操做。class
時間複雜度和空間複雜度同上,可是代碼實現過程簡化不少。耗時很是少。遍歷
class Solution { public: int maxProfit(vector<int>& prices) { int totalProfite = 0; for (size_t i = 1; i < prices.size(); i++) { if (prices[i - 1] < prices[i]) totalProfite += (prices[i]-prices[i-1]); } return totalProfite; } };