【Leetcode】买卖股票-贪心算法

匿名 (未验证) 提交于 2019-12-03 00:14:01

题目:

设计一个算法来计算你所能获取的最大利润。你可以尽可能地完成更多的交易(多次买卖一支股票)。

注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。

思路:

采用贪心算法,如果当天股票的价格 pi 大于等于前一天的股票价格 pi-1 则持续持有。如果低于前一天的价格,则在前一天就抛售股票。

时间复杂度:O(N)。从头遍历每一天的股票价格。

空间复杂度:O(1)。

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 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;     } };

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!