[leetcode] 121. Best Time to Buy and Sell Stock

来源:互联网 发布:网络用语你妹什么意思 编辑:程序博客网 时间:2024/05/21 13:52

题目:
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.
题意:
你拥有股票在k天的价格,寻找一个买入和卖出的时间,使受益最大。当然买入时间肯定需要早于等于卖出时间。
思路:
使用动态规划,我是从后面一天往前推算,profit[i]代表的是从第i天到最后一天的最大收益,并且保存从第i天到最后一天的价格的最大值max_price,对于计算profit[i-1],如果price[i-1] > max_price,那么更新max_price。并且profit[i-1] = profit[i].否则profit[i-1] = max(profit[i], max_price - price[i-1])。
以上。
代码如下:

class Solution {public:    int maxProfit(vector<int>& prices) {        if(prices.size() == 0)return 0;        int * profit = new int[prices.size()];        int max_price = prices[prices.size() - 1];        profit[prices.size() - 1] = 0;        for(int i = prices.size() - 2; i >= 0; i--){            if(prices[i] > max_price) {                max_price = prices[i];                profit[i] = profit[i + 1];            }            else {                profit[i] = max(profit[i + 1],max_price - prices[i]);            }        }        return profit[0];    }};
0 0
原创粉丝点击