Best Time to Buy and Sell Stock II

题目:Say you have an array for which the ith 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).


思路:贪心

贪心算法,只要我当前价格比之前的高,那我就卖了,我可以再买。后期我再买,用一个sum的全局变量。

代码:

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        //贪心法,只要后面一天比前面一天价格高,就卖。然后再买。
        //最简单的算法
        if(prices.empty()){
            return 0;
        }
        
        int sum=0;
        for(int i=1;i<=prices.size()-1;i++){
            if(prices[i]>prices[i-1]){
                sum=sum+prices[i]-prices[i-1];
            }
        }
        
        return sum;
    }
};


posted @ 2015-10-11 16:45  JSRGFJZ6  阅读(89)  评论(0编辑  收藏  举报