4/13/2014

Leetcode -- Best Time to Buy and Sell Stock II

This one is simple, we just need to sum all the difference of non-decreasing prices.
 class Solution {  
 public:  
   int maxProfit(vector<int> &prices) {  
     if(prices.empty()) {  
       return 0;  
     }  
     int profit = 0;  
     int diff = 0;  
     for(int i = 0; i < prices.size() - 1; ++i) {  
       if(prices[i + 1] >= prices[i]) {  
         diff += prices[i + 1] - prices[i];  
       } else {  
         profit += diff;  
         diff = 0;  
       }  
     }  
     profit += diff;  
     return profit;  
   }  
 };  

No comments: