cv_gordon

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: :: :: 管理 ::

题目:

给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。

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

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

 

 

思路:

采用贪心算法,如果当天股票的价格 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;
    }
};

 

posted on 2019-10-11 11:23  cv_gordon  阅读(2182)  评论(0编辑  收藏  举报