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
- 1 ≤ prices.length ≤ 10⁵
- 0 ≤ prices[i] ≤ 10⁴
- You must buy before you sell
Edge cases to test
- Prices only fall: profit
0 - One day
- The cheapest day comes after the most expensive one
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 bestC++
#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
- Minimum Size Subarray Sum (Medium)
- Maximum Sum Subarray of Size K (Easy)
- Max Consecutive Ones III (Medium)
- Fruit Into Baskets (Medium)
- Longest Substring Without Repeating Characters (Medium)
- Longest Repeating Character Replacement (Medium)
- Permutation in String (Medium)
- Find All Anagrams in a String (Medium)
- Minimum Window Substring (Hard)
- Subarrays with K Different Integers (Hard)