LeetCode

Best Time to Buy and Sell Stock

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

public class Solution {
    public int maxProfit(int[] prices) {
        if(prices.length < 0) {
            return 0;
        }

        int minPriceIndex = 0;
        int maxProfit = 0;

        for(int i = 0; i < prices.length; i++) {
            if(prices[i] < prices[minPriceIndex]) {
                minPriceIndex = i;
            }

            int val = prices[i] - prices[minPriceIndex];

            if(maxProfit < val) {
                maxProfit = val;
            }
        }

        return maxProfit;
    }
}