Leetcode: Best time to buy and sell stock

 This question is considered an "easy" question, yet I keep getting it over and over and over again, and is asked at Amazon, Microsoft, Apple, Facebook, Google, among many other companies. Here's the question:



Say you have an array for which the ith element is the price of a given stock on day i.  If you were only permitted to complete at most one transaction (buy one and sell ons share of the stock), design an algorithm to find the maximum profit. 


How do we solve this? We can solve this using 2 ways, a brute force approach and a one-pass approach. Obviously a brute force works for simple cases, where you just update a maxprofit whenever a days value is greater than the other difference, but not in every case, especially when you have millions of price differentials.

Anyways, here's the brute force solution.

public class Solution {

    public int maxProfit(int prices[]) {

        //maximum profit

        int maxprofit = 0;

        for(int i = 0; i < prices.length - 1; i++) {

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

                //compare the price difference to total profit. If more, update the profit.

                int profit = prices[j] - prices[i];

                if(profit > maxprofit) profit = maxprofit;

            }

        } 

        return maxprofit;

    }

}


This is computationally complex, since the loop runs n(n-1)/2 time and n space since only 2 variables are asked for. We can go through a single pass and update the minimum element every time we see a value less than the minimum value, otherwise if we see that we sense a potential maximum profit, we change this correspondingly. So, we always check for lesser minimum prices while simultaneously checking for a maximum profit update if there is a price that far exceeds the maximum profit, such is the theory of one-pass. It just moves the 2 pointers, minimum and maximum, and recording the values by constantly changing the reference points. Here is the solution: 

public class Solution {

    public int maxProfit(int prices[]){

        //minprice is always compared and goes less now.  

        int minprice = Integer.MAX_VALUE;

        //maximum profit always increases and is positive.

        int maxprofit = 0;

        for(int i = 0; i < prices.length; i++) {

            //If price is less than the minimum price, update the price

            if(prices[i] < minprice) 

                minprice = prices[i];

            //else if we have a greater differential, update the maximum profit. 

            else if(prices[i] - minprice > maxprofit) maxprofit = prices[i] - minprice;

        }

        return maxprofit;

    }

}


Comments

Popular Posts