DevPath

← All problems

Best Time to Buy and Sell Stock

Easy arrays · greedy

Description

Given prices by day, return the maximum profit from buying on one day and selling on a later day. If no profit is possible, return 0.

Constraints

1 <= n <= 100000; 0 <= price

Examples

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

Output: 5

Buy at 1, sell at 6

Hints (1)
  • Track the minimum price so far while scanning.

Solutions

Track running minimum and best profit. · Time O(n) · Space O(1)

func maxProfit(prices []int) int {
    low := 1 << 62
    best := 0
    for _, p := range prices {
        if p < low {
            low = p
        } else if p-low > best {
            best = p - low
        }
    }
    return best
}

Create a free account to submit solutions, track progress and save problems.

Create account