Sunday, June 4, 2017

Best time to buy and sell a stock II

Problem Statement

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).
Link to GitHibCode


Solution


  • We need a variable to store the maxProfit
  • We need to iterate through the array and Get the difference between selling price and buying price  maxprofit+=prices[i+1]-prices[i]
  • We need to make sure that selling price is greater than buying price. This check can be done using if condition if(prices[i+1] >prices[i])
 public static int get(int [] prices)
 {
  int maxprofit=0;
  //loop through the array set . We need to keep on adding the profit
  //We need to buy and sell before buying others
  for(int i=0;i<prices.length-1;i++)
  {
   //We need to make sure that selling is greater than profit
   if(prices[i+1] >prices[i])
   {
    maxprofit+=prices[i+1]-prices[i];
   }
  }
  return maxprofit;
  
 }

No comments:

Post a Comment