Leetcode problem 121. 'Best time to buy and sell stock'

class Solution {
    public int maxProfit(int[] prices) {
        if (prices == null || prices.length == 0)
            return 0;

        int minPrice = Integer.MAX_VALUE;
        int maxProfit = 0;

        for (int i = 0; i < prices.length; i++) {
            if (prices[i] < minPrice) {
                minPrice = prices[i];
            } else if (prices[i] - minPrice > maxProfit) {
                maxProfit = prices[i] - minPrice;
            }
        }

        return maxProfit;
    }
}

Comments

Popular posts from this blog

Tic-Tac-Toe Game in Java

Finding Subarrays with a Target Sum in Java: A Beginner's Guide

Majority Element in a Array