[leetcode] best time to buy and sell stocks

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.

O(n)的算法。。。没什么好说的

  
  
  
  
  1. int maxProfit(vector<int> &prices) { 
  2.     // Start typing your C/C++ solution below 
  3.     // DO NOT write int main() function 
  4.     if(prices.empty()) return 0; 
  5.      
  6.     int minVal = prices[0]; 
  7.     int result = 0; 
  8.      
  9.     for(int i = 1; i < prices.size(); i++){ 
  10.         if(prices[i] > minVal){ 
  11.             result = MAX(result, ( prices[i] - minVal)); 
  12.         }else
  13.             minVal = prices[i]; 
  14.         } 
  15.     } 
  16.      
  17.     return result; 

 

你可能感兴趣的:(LeetCode)