Algo-Sim › Sliding Window

Best Time to Buy and Sell Stock

Easy · Sliding Window · step through it in Java, Python and C++ on your own input

Find the largest profit from one buy and a later sell: the buy day only ever moves to a cheaper price.

Problem

You are given prices, where prices[i] is the price of a stock on day i. Choose one day to buy and a later day to sell, and return the largest profit you can make. If no trade makes money, return 0.

Constraints

Edge cases to test

Follow-up questions

What if you may buy and sell as many times as you like?
Add every positive day-to-day rise (LC 122): O(n) time, O(1) space.
What if there is a fee or a cooldown?
Track a "holding" and a "not holding" state per day (a two-state DP, LC 714 and 309): still O(n) time and O(1) space.
What if prices stream in?
Keep the running minimum and the best profit so far: O(1) per price.

Solution

Java

public int maxProfit(int[] prices) {
    int left = 0, best = 0;
    for (int right = 1; right < prices.length; right++) {
        if (prices[right] < prices[left]) {
            left = right;
        } else {
            best = Math.max(best, prices[right] - prices[left]);
        }
    }
    return best;
}

Python

def max_profit(prices):
    left, best = 0, 0
    for right in range(1, len(prices)):
        if prices[right] < prices[left]:
            left = right
        else:
            best = max(best, prices[right] - prices[left])
    return best

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    int maxProfit(vector<int> &prices) {
        int left = 0, best = 0;
        for (int right = 1; right < int(prices.size()); right++) {
            if (prices[right] < prices[left]) {
                left = right;
            } else {
                best = std::max(best, prices[right] - prices[left]);
            }
        }
        return best;
    }
};

More Sliding Window problems