Tuesday, September 17, 2013

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:
太简单了,把爷们儿给吓着了。
就是,把所有的,difference > 0的加起来就行了。

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int res = 0;
        if( prices.size()==0)
            return 0;
        for(int i =0; i< prices.size()-1; ++i)
        {
            int diff = prices[i+1] - prices[i];
            res += max(0, diff);
        }
        return res;
    }
};

Mistakes:
不知道为什么,不加 
if( prices.size()==0)
            return 0;
LC就会报错。说     AddressSanitizer:DEADLYSIGNAL    很奇怪


-----------------------第二遍---------- 每次找一个最小的,然后找其卖出点

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int n = prices.size();
        if(n==0)
            return 0;
        
        int res = 0;
        int preMin = -1; // not buy yet if negative
        for(int i= 0; i< n; ++i) 
        {
            int v = prices[i];
            if(preMin <0 || v<preMin)
            {
                preMin = v;
            }else
            {
                if(i+1 < n && prices[i+1] > v) // if we can go further
                {
                    continue;
                }else{
                    res += v-preMin;
                    preMin = -1;
                }
            }
        }
        return res;
    }
};

No comments:

Post a Comment