Coding

Best Time to Buy and Sell Stock

You have access to an array where each element represents the price of a specific stock on a given day. Your objective is to maximize profit by selecting one day to purchase the stock and a different, future day to sell it. Determine and return the maximum profit achievable. If it's impossible to generate a profit, return 0.

Input: prices = [9,3,8,2,7,5]

Output: 5

Explanation: Purchase on day 2 (price = 3) and sell on day 5 (price = 7) for a profit of 7 - 3 = 4.

Software EngineerEngineering ManagerMachine Learning EngineerProduction Engineer

Dropbox

Meta

Palo Alto Networks

Spotify

Square

Uber

Did you come across this question in an interview?

Answers

Expert Answer

Anonymous

4.6Exceptional
const getMaxProfit= (arr) => {
    let minPrice = Infinity;
    let maxProfit = 0;
    
    for(let price of arr) {
        if(price < minPrice) {
            minPrice = price;
        } else {
            maxProfit = Math.max(maxProfit, price - minPrice);
        }
    }
    return maxProfit
}
Try Our AI Interviewer

Prepare for success with realistic, role-specific interview simulations.

Try AI Interview Now

Interview question asked to Site Reliability Engineers, Software Engineers, Production Engineers and other roles interviewing at CarMax, Adobe, Agoda and others: Best Time to Buy and Sell Stock.