Abhishek-Chaudhary-InfoCepts
11/18/2018 - 6:34 AM

BuySellStocks.java

package com.abhishek.dojo;

public class BuySellStocks {

	public static void main(String[] args) {

		BuySellStocks bss = new BuySellStocks();
		// case 1- stock price always increasing
		// you need to buy first and sell later
		// Lowest buy value- 10
		// Highset sell value- 50
		// Answer- 40
		bss.getMaxProfit(new int[] { 10, 20, 30, 40, 50 });

		// case 2- stock price fluctuating
		// Starts with high, very low at middle of day and then low at end of the day
		// you need to buy first and sell later
		// Lowest buy value- 30
		// Highset sell value- 10
		// Answer = 20
		bss.getMaxProfit(new int[] { 10, 20, 30, 5, 6 });

		// case 3- stock price fluctuating
		// Starts with low, very high at middle of day and then low at end of the day
		// you need to buy first and sell later
		// Lowest buy value- 5
		// Highset sell value- 120
		// Answer = 115
		bss.getMaxProfit(new int[] { 100, 20, 30, 5, 15, 100, 120, 110 });

		// case 3- stock price decreasing all day
		// you need to buy first and sell later
		// Lowest buy value- 100
		// Highset sell value- 90
		// Answer = -10
		bss.getMaxProfit(new int[] { 100, 90, 80, 70, 60 });
	}

	// How are you ensuring that buy first and sell later happens?
	// at every point we are keepign track of the lowest price we have seen so far
	// and then max profit

	// approach uses 2 initial variables- max and min profit
	// one inner variable for current price
	// one variable to store potential profit
	// update max profit
	// update min price
	public int getMaxProfit(int[] stockPrice) {

		if (stockPrice.length < 2) {
			throw new IllegalArgumentException();
		}
		int minPrice = stockPrice[0];
		int maxProfit = stockPrice[1] - stockPrice[0];

		for (int i = 1; i < stockPrice.length; i++) {

			int currentPrice = stockPrice[i];

			int potentialProfit = currentPrice - minPrice;

			maxProfit = Math.max(potentialProfit, maxProfit);

			minPrice = Math.min(currentPrice, minPrice);

		}
		System.out.println("max profit: " + maxProfit);
		return maxProfit;
	}

}