import java.util.*;
import java.lang.*;
import java.io.*;
class StockPricesIntrospection
{
public static void main (String[] args) throws java.lang.Exception
{
// Test Input here
int[] inputArr = new int[] {38, 40, 42, 35, 23, 50};
int size = inputArr.length;
int[][] maxValuesFrom = new int[6][6];
for( int start=0; start < size-1; start++)
{
int minimumStartingPrice = inputArr[start];
int maximumEndingPrice = inputArr[start];
for( int end=start+1; end < size; end++)
{
if( maximumEndingPrice < inputArr[end] )
{
maximumEndingPrice = inputArr[end];
}
maxValuesFrom[start][end] = ( maximumEndingPrice - minimumStartingPrice );
}
}
int finalMaxStockPrice=0;
for( int startIndex=0; startIndex < size; startIndex++)
{
int localMax=maxValuesFrom[startIndex][size-1];
for(int endIndex=startIndex+1; endIndex < size; endIndex++)
{
int sumValue;
if ( endIndex == size - 1 )
{
sumValue = localMax;
}
else
{
sumValue = maxValuesFrom[startIndex][endIndex] +
maxValuesFrom[endIndex+1][size-1];
}
if( sumValue > maxValuesFrom[startIndex][size-1] && sumValue > localMax )
{
localMax = sumValue;
}
}
if( finalMaxStockPrice < localMax )
{
finalMaxStockPrice = localMax;
}
}
System.out.println("Max stock price profit could have been " + finalMaxStockPrice);
}
}
Time complexity: O( n squared)
Space complexity: O(n squared)
Test Execute it here.
No comments:
Post a Comment