码迷,mamicode.com
首页 > 其他好文 > 详细

【leetcode】121. Best Time to Buy and Sell Stock

时间:2015-07-19 21:45:13      阅读:121      评论:0      收藏:0      [点我收藏+]

标签:leetcode   dp   最大连续子序列和   

@requires_authorization
@author johnsondu
@create_time 2015.7.19 21:01
@url [best time to buy and sell stock](https://leetcode.com/problems/best-time-to-buy-and-sell-stock/)
/************************
 * @description: dynamic programming.
 *    相邻元素做差,然后转化为最大连续子序列和
 * @time_complexity:  O(n)
 * @space_complexity: O(n)
 ************************/
class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int p_size = prices.size();
        if(p_size < 2) return 0;
        vector<int> dp;
        for(int i = 1; i < p_size; i ++)
            dp.push_back(prices[i] - prices[i-1]);

        int ans = 0;
        int cur = 0;
        int dp_size = dp.size();
        for(int i = 0; i < dp_size; i ++){
            cur = cur + dp[i];
            if(cur < 0) cur = 0;
            if(cur > ans) ans = cur;
        }

        return ans;
    }
};

版权声明:本文为博主原创文章,未经博主允许不得转载。

【leetcode】121. Best Time to Buy and Sell Stock

标签:leetcode   dp   最大连续子序列和   

原文地址:http://blog.csdn.net/zone_programming/article/details/46958309

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!