Skip to content
    SeaCode
    Learning tracksCode ArenaWorkshops & EventsInstructors
    Log inSign up
    Practice problems / Best time to buy and sell

    Best time to buy and sell

    Easyarraygreedysliding window

    prices[i] is a stock's price on day i. Buy on one day and sell on a later day. Return the maximum profit, or 0 if none is possible.

    Example 1

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

    Buy at 1, sell at 6.

    Example 2

    Input:  prices = [7,6,4,3,1]
    Output: 0

    Constraints

    • 1 ≤ prices.length ≤ 10⁵
    • 0 ≤ prices[i] ≤ 10⁴

    Submit checks your solution against 7 tests, including hidden ones.

    /**
     * @param {int[]} prices
     * @return {int}
     */
    function maxProfit(prices) {
      
    }
    
    Sign in to run
    SeaCode

    Learn to code for real, online or at our branch in front of Cairo University, Giza.

    Learn

    • All courses
    • Interactive tutorials
    • Interview practice problems
    • Mock interview
    • Learning tracks
    • Code Arena
    • Workshops & Events
    • Knowledge library
    • Team projects

    Your account

    • Log in
    • Sign up
    • Learning plan
    • Certificates
    • Site map

    Contact us

    • WhatsApp
    • 010 9094 1104
    • In front of Cairo University, Giza

    © 2026 SeaCode. All rights reserved.