Best Time to Buy and Sell Stock

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.

 

Analyse: dp[i] = max(dp[i-1], prices[i] - lowest[0,..., i-1]).

Runtime: 8ms.

 1 class Solution {
 2 public:
 3     int maxProfit(vector<int>& prices) {
 4         const int n = prices.size();
 5         if(n == 0) return 0;
 6         
 7         int dp[n] = {0};
 8         int lowest = prices[0];
 9         for(int i = 1; i < prices.size(); i++){
10             dp[i] = max(dp[i - 1], prices[i] - lowest);
11             lowest = min(lowest, prices[i]);
12         }
13         return dp[n - 1];
14     }
15 };

 

or 

 

 1 class Solution {
 2 public:
 3     int maxProfit(vector<int>& prices) {
 4         if(prices.size() <= 1) return 0;
 5         
 6         int result = 0, pre = 0;
 7         int lowest = prices[0];
 8         for(int i = 1; i < prices.size(); i++){
 9             result = max(pre, prices[i] - lowest);
10             lowest = min(lowest, prices[i]);
11             pre = result;
12         }
13        return result;
14     }
15 };

 

posted @ 2015-08-20 03:33  amazingzoe  阅读(119)  评论(0编辑  收藏  举报