clueless coding // TODO: be smarter

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



Problem Statement


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

If you could only complete at most one transaction (i.e, buy one and sell one share of the stock), write a function to find the maximum profit.

Function Signature (C++):
  int maxProfit(vector<int>& prices)

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

Outputs:
  5

We can buy at 1 and then sell at 6 => 6 - 1 = 5;

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

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

Outputs:
  0

No transaction is done - we would only lose money.



TL;DR Code Solution


int maxProfit(vector<int>& prices) {

    int currentMin = INT_MAX;
    int result = 0;

    for (int i = 0; i < prices.size(); i++) {
        result = max(result, prices[i] - currentMin);
        currentMin = min(currentMin, prices[i]);
    }

    return result;

}