Leetcode–Best Time to Buy and Sell Stock

The Problem:

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.

Notes:

  1. Keep track of max profit if sell at day i, and a min price to buy before day i.

Java Solution

public class Solution {
    public int maxProfit(int[] prices) {
        if(prices.length <=1)
            return 0;
        int maxProfit = 0;
        int minP = prices[0];
        for(int i = 1; i < prices.length; i++){
            maxProfit = Math.max(maxProfit, prices[i]-minP);
            minP = Math.min(minP, prices[i]);
        }
        return maxProfit;
    }
}

Leave a comment