Friday, March 20, 2015

122. Best Time to Buy and Sell Stock II Leetcode Java

Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
This problem is easier than the previous one: Best Time to Buy and Sell Stock
Because, this problem allows multiple transactions, so any profitable transaction is allowed for each day. So the easier way is if prices[i]>prices[i-1], we buy it on (i-1)th day and sell it on ith day. Otherwise, don't buy the stock(or buy it and sell it on the same day). 
 public int maxProfit(int[] prices) {  
    int res=0;  
    for(int i=1;i<prices.length;i++){  
      res+=(prices[i]>prices[i-1])? prices[i]-prices[i-1]:0;  
    }  
    return res;  
   }  

No comments:

Post a Comment