The O(n) Club: Stock Profiteering With Pac-Man Instincts

The O(n) Club: Stock Profiteering With Pac-Man Instincts

⚡ TL;DR

Every time your stock inches up, cash out the difference. Don’t stare wistfully at the chart waiting for The Perfect Trade. Scoop every uptick and move on—like a caffeinated Pac-Man mowing down power pellets of profit:

// Java one-line greediness
int maxProfit(int[] prices) {
    int profit = 0;
    for (int i = 1; i < prices.length; i++)
        if (prices[i] > prices[i - 1])
            profit += prices[i] - prices[i - 1];
    return profit;
}

🧠 How Devs Usually Mess This Up

Raise your hand if you tried to build a Timeline of Every Trade, complete with buy and sell dates, like a suspicious accountant with too many spreadsheets. Or maybe you reached for your trusty DP table, refusing to believe something so easy could pay off. It can’t be THAT simple, right? (Wrong. Sometimes, life—and LeetCode—are, shockingly, straightforward.)

🔍 What’s Actually Going On

The stock market does not reward patience here—it rewards hustle. For this problem, you are not Warren Buffet, you are Pac-Man: at every little uptick between consecutive days, gobble up that profit immediately. You’re not on Wall Street planning huge mergers; you’re in an arcade, stuffing quarters and taking every win you can spot. The sum of small, shameless wins beats holding out for perfection.

Algorithmic traders and sneaker resellers do this daily: it’s not about getting rich off one big score, but accumulating a heap of micro-wins. The magic? If you collect every little increase, your pile equals the biggest gain you could’ve dreamed up, minus the drama.

🛠️ PseudoCode

  • Set profit = 0. (Everyone starts somewhere.)
  • Loop i from 1 → end:
    • If prices[i] > prices[i-1],
      • profit += prices[i] - prices[i-1]; (You chomp out another win.)
    • Else, skip. (You cannot lose money by doing nothing, unless you work in crypto.)
  • Return profit. (Brag to your manager.)
Previous Article

The O(n) Club: Maximal Square: When DP Plays Tetris With Your Sanity

Next Article

The O(n) Club: Minimum Path Sum: Grid Torture for People Who Hate Left Turns