Wednesday, August 26, 2015

[Greedy] Best Time to Buy and Sell Stock II

1. Example

s is array of price at each day
s = [$10, $50, $60, $20, $5, $40]
Find the maximum profit?
You may complete as many as transactions as you like.
Not multiple transaction at the same time, which means you must sell stock before you buy again.

2. Implementation
Q1: maximum profit?
A1: accumulate every profit opportunity
Q1: can i buy at the lowest price and sell at the highest?
A1: only one transaction.
Q1: buy before sell ?
A1: we cannot find every large gap to do the transaction since they are probably not in chronological order. So check every transaction and if profitable, we do it.


// Time:O(n), Space:O(1)
public int maxProfit(int[] prices)
{

      // validate the input
      if (  prices == null || prices.length== 0)
      { 
         return 0;
      }



      int profit = 0;
      for (int i =1; i < prices.length ; i++)
      {
            ((prices[i] - prices[i-1]) > 0 )? profit += (prices[i] - prices[i-1]): continue;
      }



      return profit;
}

3. Similar Ones
Best Time to Buy and Sell Stock
Best Time to Buy and Sell Stock III
Best Time to Buy and Sell Stock IV

No comments:

Post a Comment