Easy Problems

121. Best Time to Buy and Sell Stock

What will be learned

  • Understand the idea of maintaining state variables through an array to solve optimization problems.

Solutions

function maxProfit(prices: number[]): number {
   let max = 0;
   let profit = 0;
   for(let i = 0; i < prices.length; i++) {
       for(let j = i + 1; j < prices.length; j++) {
           profit = prices[j] - prices[i]
           if(profit > max) {
               max = profit
           }
       }
   }
   return max;
};

Video Solution

Last Update: 12:08 - 16 April 2024
Array
Dynamic Programming

On this page