您的位置:首页 > 其它

leetcode-122 Best Time to Buy and Sell Stock II

2015-04-26 21:52 447 查看
这题要求可以交易任意多次,其实就是找递增子序列

例如:1 3 4 9 5 8 2 1 3

则 9 - 1 + 8 - 5 + 3 - 1

注意条件的判断不要写错啦

<span style="font-family:Microsoft YaHei;font-size:14px;">class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int len = prices.size();
        if(len == 0) return 0;
        int maxProfit = 0;
        int min = prices[0];
        for(int i = 1; i < len; i++){
            if(prices[i] < min) min = prices[i];
            else if( (prices[i] > min) && (i == len -1)){
                maxProfit += prices[i] - min;
            }else if( (prices[i] > min) && (prices[i+1] < prices[i])){
                maxProfit += prices[i] - min;
                min = prices[i+1];
            }
        }
        return maxProfit;
    }
};</span>


discuss里面更简单的方法:感觉怪怪的


Is this question a joke?

<span style="font-family:Microsoft YaHei;font-size:14px;">class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int len = prices.size();
        if(len == 0) return 0;
        int maxProfit = 0;
        for(int i = 0; i < len - 1; i++){
            if(prices[i+1] > prices[i]) maxProfit += prices[i+1] - prices[i];
        }
        return maxProfit;
    }
};</span>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: