【ATT】Best Time to Buy and Sell Stock II

Q: 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).

A: 可以买卖股票多次,同时如果已经买了股票,那么接下来只能先卖了股票再买股票,一天只能执行买卖一次。

    int maxProfit(vector<int> &prices) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if(prices.empty())
            return 0;
        
        int diff;
        int mprofit = 0;
        
        for(int i=1;i<prices.size();i++)
        {
            diff = prices[i] - prices[i-1];
            if(diff>0)
                mprofit+=diff;
        }
        
        return mprofit;
        
    }

  

posted @ 2013-09-19 23:50  summer_zhou  阅读(149)  评论(0编辑  收藏  举报