LeetCode – Best Time to Buy and Sell Stock (Java)

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 (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

Java Solution

Instead of keeping track of largest element in the array, we track the maximum profit so far.

public int maxProfit(int[] prices) {
    if(prices==null||prices.length<=1)
        return 0;
 
    int min=prices[0]; // min so far
    int result=0;
 
    for(int i=1; i<prices.length; i++){
        result = Math.max(result, prices[i]-min);
        min = Math.min(min, prices[i]);
    }
 
    return result;
}

11 thoughts on “LeetCode – Best Time to Buy and Sell Stock (Java)”

  1. obv , this is ripe for div/conq

    find on left side min, find on right side max
    call left side
    call right side

    combine

    but it is o(nlgN)

  2. Your “fails” can be fixed by simply setting the initial value of profit to prices[1] – prices[0] to get the maxProfilt / smallest lost

  3. Not the first element has the highest value but elements in the array are in descending order, and this can be solved by setting the initial value of profit to prices[1] – prices[0] to get the maxProfilt / smallest lost

  4. Inner for loop of naive solution must start from i and not 0. When buying a stock you can only see future values to sell it 🙂

  5. Thanks for the nice post. But first solution fails at int[] price2 = {100, 90, 80, 70, 60};
    It should be:
    public static int maxProfit5(int[] array) {
    if(array == null || array.length < 2){
    return 0;
    }
    int maxProfit = 0;
    for(int i = 0; i < array.length-1; i++){
    for(int j = i+1; j array[i] && maxProfit < array[j] - array[i]){
    maxProfit = array[j] - array[i];
    }
    }
    }
    return maxProfit;
    }

  6. See my solution:

    public int maxProfit(int[] p) {

    if(p == null || p.length<=1) return 0;

    int len = p.length;

    int max = p[0];

    int min = p[0];

    int profit = 0;

    for(int i=1; i max) {

    max = p[i];

    }

    if(p[i] < min) {

    min = p[i];

    max = p[i];

    }

    profit = Math.max(max – min, profit);

    }

    return profit;

    }

  7. Dynamic programming solution. O(n) time complexity, O(n) space

    public int maxProfit(int[] prices) {

    if(prices.length == 0) return 0;

    int[] profit = new int[prices.length];

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

    profit[i] = 0;

    }

    int min = prices[0];

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

    if(prices[i] < min) min = prices[i];

    profit[i] = Math.max(profit[i-1], prices[i]-min);

    }

    return profit[prices.length-1];

    }

  8. The efficient approach wont’ calculate correctly if the fist element in the array has the highest value

Leave a Comment