Learn-dsa..in 30 days!



























CC-5 : Find maximum profit achievable if given an array with daily stock prices.

Description:

Given an input integer array arr, where each array element represents the price of the stock on that day, find the maximum achievable profits by buying and selling that stock within the price range of the elements of the array.

Test cases and expected outputs:

Input Parameters Expected outputs
Stock price daily price arr={100,110,120,115,110,100,90} 20
Stock price daily price arr={100,90,70,80,90,110} 40
Stock price daily price arr={100,100,100,100} 0
Stock price daily price arr={ 100,120,90,115,125,95,130} 40

Pseudocode:

The java method should accept following input parameters: arr (int array). The array should contain day-wise stock price of a stock.
We need a minimum price at which we will buy stock, so initialize an int variable minStockPrice. Set it to max integer value possible in java.
Initialize two int variables maxProfit and todaysProfit to 0.
Iterate through the array of daily prices using a for loop:
Set todaysProfit=arr[idx]- minStockPrice, to get profit we will get if the stock is sold at the price in the current index in arr.
If todaysProfit > maxProfit, set maxProfit to todaysProfit, this way maxProfit will hold the greatest possible profit we can earn.
If stock price at current index is less than minStockPrice, then set minStockPrice to today’s stock price, this way minStockPrice will hold the minimum possible price of stocks in arr.
After the loop ends return maxProfit , as this is the max profit that be earned based on the day wise stock prices in the array.

Code:

public int arrayStockMarketMaxProfit(int[] arr) throws Exception{
	int minStockPrice=Integer.MAX_VALUE;
	int maxProfit=0;
	int todaysProfit=0;
	for (int idx=0; idx < arr.length; idx++) {
		todaysProfit=arr[idx]-minStockPrice;
		if (todaysProfit > maxProfit) {
			maxProfit=todaysProfit;
		}
		if (arr[idx] < minStockPrice) {
			minStockPrice=arr[idx];
		}
	}
	return maxProfit;
}

Click here to download and run code and test cases !