首页 > 其他 > 详细

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

时间:2015-05-11 16:03:00      阅读:195      评论:0      收藏:0      [点我收藏+]

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.

题目分析:

做的时候,想用动态规划做,当时写不出比较好表达地递推式。因为最大值和最小值有一个前后关系:某一时刻最大值定下来后,想再移动最小值,则此时最大值也要改变,若只要改变最大值,最小值不受影响。这样子比较会比较混乱。

改变思路:从后往前遍历,到下标i时,则表示第i天买入,这样赚到的最大利润是i+1天~n-1填最大股价减去第i天的。

 1 class Solution {
 2 public:
 3     int maxProfit(vector<int>& prices) {
 4         //if (0 == prices.size())     return 0;
 5         int length = prices.size();
 6         int result = 0;
 7         int maxPrice = result;
 8         for (int i = length - 1; i >= 0; --i)
 9         {
10             maxPrice = max(maxPrice, prices[i]);
11             result = max(result, maxPrice - prices[i]);
12         }
13         return result;
14     }
15 };
198 / 198 test cases passed.
Status: 

Accepted

Runtime: 11 ms
Submitted: 0 minutes ago

 

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

原文:http://www.cnblogs.com/helloWaston/p/4494797.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!