clueless coding // TODO: be smarter

LeetCode 121. Best Time to Buy and Sell Stock: Java Solution



Problem Statement


You are given an array for which the ith element is the price of a stock on day i.

Assume you can only complete at most one transaction (i.e, buy one and sell one share of the stock). Design a function to find the maximum profit that you could make.

Function Signature (Java):
  int maxProfit(int[] prices)

Inputs:
  prices = [10, 1, 5, 2, 8, 1]

Outputs:
  5

We can buy at 1 and then sell at 8 => 8 - 1 = 7;

Note that the answer is not from 10 - 1, because we cannot buy at 1 and then sell at 10.

Inputs:
  prices = [7, 6, 4, 3, 1]

Outputs:
  0

No transaction is done - we would only lose money.



TL;DR Code Solution


public int maxProfit(int[] prices) {

    int max = 0;
    int bought = Integer.MAX_VALUE;

    for (int i = 0; i < prices.length; i++) {
        max = Math.max(max, prices[i] - bought);
        bought = Math.min(bought, prices[i]);
    }

    return max;

}