Best Time to Buy and Sell Stock
You get a share's price for each day. Buy it on one day and sell it on a later day, once. Return the largest profit you can make, or 0 if every trade loses. Our example: [4, 10, 7, 2, 9, 1, 3] — the answer is 7: buy at 2 on day 3, sell at 9 on day 4.
- input
prices: the price of a stock day by day,prices[i]on dayi.- returns
- The largest profit from buying one share on one day and selling it on a later day: the largest
prices[j] − prices[i]withi < j.0if no deal makes money. - constraints
- 1 ≤ prices.length ≤ 1000
- 0 ≤ prices[i] ≤ 10⁴
- examples
- Open a test in the tests panel: it shows the input and the expected answer.
/**
* @param {number[]} prices
* @return {number}
*/
function maxProfit(prices) {
}
Ctrl ↵
format
reset
saved in this browser
Stuck?
See the solution run step by step on our example, then why it works and its complexity.
Next: more dynamic programming (dp) problems
- 70Climbing StairsEasysolve
- 198House RobberMediumsolve
- 322Coin ChangeMediumsolve
- 300Longest Increasing SubsequenceMediumsolve
- 62Unique PathsMediumsolve
- 1143Longest Common SubsequenceMediumsolve
- 53Maximum SubarrayMediumsolve
- 918Maximum Sum Circular SubarrayMediumsolve
- 139Word BreakMediumsolve
- 120TriangleMediumsolve
- 64Minimum Path SumMediumsolve
- 63Unique Paths IIMediumsolve
- 97Interleaving StringMediumsolve
- 72Edit DistanceMediumsolve
- 221Maximal SquareMediumsolve
- 123Best Time to Buy and Sell Stock IIIHardsolve
- 188Best Time to Buy and Sell Stock IVHardsolve
The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.