Sunday 19 July 2015

Solution in Java for th problem : With the data for expected Stock prices for the N days, find the maximum profit that can be earned.

Hello Friends,

I am here again with another famous problem. Finding the best purchasing and selling day in stock market to earn maximum profit.

We are given an Integer Array of size N. This represents expected Stock prices for the N days.

We are required to find the maximum profit that can be earned by purchasing and selling the stock on the ideal day.

I have implemented a solution for this in Java which runs in O(n) time complexity.

For example if we have arrays such as : {250,260,200,300,150,140,135}
here maximum profit that can be earned is 100 if stocks are purchased on day 3 and selling is done on day 4.

public class MaximumStockProfit {
    public void maximumProfit(int stocks[]) {
        int n = stocks.length;
        if (n > 0) {
            int globalMaxDiff = Integer.MIN_VALUE; // to store the maximum
                                                    // profit that can be made.
            int globalLowestDay = -1; // Ideal Purchase Day
            int globalLargestDay = -1;// Ideal Selling Day

            int localMinStock = Integer.MAX_VALUE;
            int localLowestDay = -1;
            for (int i = 0; i < n; i++) {
                if (stocks[i] < localMinStock) {
                    localMinStock = stocks[i];
                    localLowestDay = i + 1; // as days are counted from 1 and
                                            // our array is 0 indexed
                }
                if ((stocks[i] - localMinStock) > globalMaxDiff) {
                    globalMaxDiff = stocks[i] - localMinStock;
                    globalLowestDay = localLowestDay;
                    globalLargestDay = i + 1;
                }
            }
            System.out.println("purchase day: " + globalLowestDay + " with price " + stocks[globalLowestDay - 1]
                    + " units selling day: " + globalLargestDay + " with price " + stocks[globalLargestDay - 1]
                    + " units max profit: " + globalMaxDiff);
        } else {
            System.out.println("Stocks data is empty");
        }
    }

    public static void main(String[] args) {
        MaximumStockProfit msp = new MaximumStockProfit();
        int stocks[] = { 2000,3000,1500,2030,4000,5010,2010,2000 };
        msp.maximumProfit(stocks);
    }
}

No comments:

Post a Comment

Hi Friends, Please leave your comments as they shall be greatest motivation , shall help me make corrections to my existing posts and will enable me to create better posts. :)