Wednesday, May 6, 2015

Best Time to Buy and Sell Stock I

来源:Leetcode

原帖:https://oj.leetcode.com/problems/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.
Solution: For each element, calculate the max difference with the former elements.

代码:
 class Solution {  
 public:  
     int maxProfit(vector<int> &prices) {  
         int minVal = prices[0], res = 0;  
         for (int i = 1; i < prices.size(); ++i) {  
             // update max profit at sell point i until the end  
             res = max(res, prices[i] - minVal);  
             minVal = min(minVal, prices[i]);  
         }  
         return res;  
     }  
 };  

No comments:

Post a Comment