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

leetcode. Best Time to Buy and Sell Stock

时间:2014-12-11 23:39:11      阅读:212      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   io   ar   color   os   使用   sp   

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.

首先,问题转换为数学语言:对数组A[n], 对任意i < j < n, 求出max(A[j] - A[i]).

可以使用O(n^2)的方法得到结果。

以下分析动态规划方法:

对于输入prices[n], 如果已知profit[i - 1], 

1) 当prices[i] <= prices[i - 1]时,显然,profit[i] = profit[i - 1]

2)当prices[i] > prices[i - 1]时, 记bottom = min(prices[0, 1, ..., i]), 如果

prices[i] - bottom > profit[i - 1] 则有
profit[i] = prices[i] - bottom

否则,profit[i] = profit[i - 1]
 1 int maxProfit(vector<int> &prices) 
 2     {
 3         int n = prices.size(), bottom, max_profit;
 4         if (n <= 1)
 5             return 0;
 6         int *profit = new int[n];
 7         profit[0] = 0;
 8         bottom = prices[0];
 9         for (int i = 1; i < n; i++)
10         {
11             bottom = min(bottom, prices[i]);
12             if (prices[i] > prices[i - 1] && prices[i] - bottom > profit[i - 1])
13             {
14                 profit[i] = prices[i] - bottom;
15             }
16             else
17             {
18                 profit[i] = profit[i - 1];
19             }
20         }
21         max_profit = profit[n - 1];
22         delete profit;
23         return max_profit;
24     }

 

leetcode. Best Time to Buy and Sell Stock

标签:des   style   blog   io   ar   color   os   使用   sp   

原文地址:http://www.cnblogs.com/ym65536/p/4158613.html

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