Thursday 24 September 2015

Maximize stock profit simple

Problem

You are given the prices of a given stock for some days. You were allowed to own at most one stock at any time and you must not hold any stock at the end of that period. Find out the maximum profit that you could have.

Solution

The strategy is to sell the stock at the end of every increasing sequence. And buy at the end of a decreasing sequence. So if at any day the stock price is greater than the previous day, the stock profits increase by the amount of that difference.

Code

public class StockPriceMaxProfitSimple {
 public static void main(String[] args) {
  int[] prices = { 400, 402, 435, 398, 378, 400, 432, 432, 402 };
  System.out.println(getMaxProfit(prices, false));
 }

 private static int getMaxProfit(int[] prices, boolean b) {
  if (prices.length == 0)
   return 0;
  int previousPrice = prices[0];
  int profit = 0;
  for (int i = 0; i < prices.length; ++i) {
   if (prices[i] > previousPrice) {
    profit += (prices[i] - previousPrice);
   }
   previousPrice = prices[i];
  }
  return profit;
 }
}

No comments:

Post a Comment