Arrays · Coding problem
Best Single Trade, Losses Allowed
A free coding problem from the Single-Pass State Tracking skill. Read it here, then solve it in the app in Java or Python.
- Easy
- Coding problem
- Free
- Java and Python
The problem
You're given daily stock prices prices. You must make exactly one trade: buy on one day and sell on a strictly later day. Return the best profit you can make, which is negative if prices only fall (then report the smallest loss).
Example
Input:
5
12 10 9 7 4
Output:
-1
Buying at 10 and selling at 9 loses 1; every other trade loses more.
This is Best Time to Buy and Sell Stock with one change: not trading is no longer an option, and that change exposes an ordering bug the classic version hides.
Constraints
2 <= prices.length <= 4 * 10^50 <= prices[i] <= 10^4- The buy day must be strictly before the sell day.
How it's graded
- Run checks your code against the examples. Submit also runs a hidden suite in four groups - basic cases, edge cases, random inputs and performance tests at the size limit - and shows which groups pass, never the hidden inputs.
- Stuck? Hints come in four steps, from a nudge to a code skeleton, each costing part of the points.
- Once you pass, you see the approaches from brute force to optimal, and where your solution lands among them.
More problems in Single-Pass State Tracking
Solve it Best Single Trade, Losses Allowed free
No card needed. Lessons, practice questions and easy problems are free forever.
Free plan, no card · 7-day Pro trial · Cancel anytime