Best Time to Buy and Sell Stock

EasyGreedy

You are given an array prices, where prices[i] is the price of a stock on day i.

You may make at most one trade: buy one share on some day and sell it on a later day. Return the largest profit you can make. If no trade makes money, return 0: you simply don't trade.

Constraints

  • 1 <= prices.length <= 10^5
  • 0 <= prices[i] <= 10^4

Examples

Example 1

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

Buy at index 3 (price 1) and sell at index 4 (price 7): a profit of 6.

Example 2

Input: prices = [9,7,4,2]
Output: 0

Prices only fall, so every trade loses money. Not trading gives 0.

Example 3

Input: prices = [2,9,1,5]
Output: 7

The lowest price, 1, comes too late: selling after it earns at most 5 - 1 = 4. Buying at 2 and selling at 9 earns 7.

JavaScript you'll use: Numbers, Math and integer tricks Arrays: create, read, update

/**
 * @param {number[]} prices
 * @return {number}
 */
function maxProfit(prices) {
  
}

Ctrl/⌘ + ' runs the examples, Ctrl/⌘ + Enter submits. Use console.log freely: output shows under Console. In the editor, press Esc then Tab to move focus out.