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

题目:算法

给定一个数组,它的第 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;
    }
};
相关文章
相关标签/搜索