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

Leetcode Best Time to Buy and Sell Stock

时间:2014-06-25 13:06:16      阅读:198      评论:0      收藏:0      [点我收藏+]

标签:des   style   class   blog   code   color   

Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

一开始看到题目以为是最大值减去最小值即可,但由于买发生在卖前面,所以,最小值买进最大值卖出只有在最小值在最大值前面时才发生

本题思路是:遍历时记录前面最小值点,然后max(当前元素-前面最小值)即可

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

本题也可以考虑利用动态规划去做

设决策变量为dp[i],表示i个元素卖出的最大利润

则状态转移方程为

  dp[i+1] = prices[i+1]-prices[i]+max(0,dp[i])

由于前面的dp[i],在dp[i+1]后不会被使用,故只需要一个状态变量,不断更新这个状态变量即可

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

 

 

Leetcode Best Time to Buy and Sell Stock,布布扣,bubuko.com

Leetcode Best Time to Buy and Sell Stock

标签:des   style   class   blog   code   color   

原文地址:http://www.cnblogs.com/xiongqiangcs/p/3806803.html

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