Algo-Sim › Greedy
Best Time to Buy and Sell Stock II
Medium · Greedy · step through it in Java, Python and C++ on your own input
Any number of trades, one share at a time: the best profit is the sum of every positive day-to-day rise.
Problem
You are given prices, where prices[i] is the price of a stock on day i. Each day you may buy and/or sell, but you can hold at most one share at a time. You may complete as many transactions as you like. Return the maximum profit.
Constraints
- 1 ≤ prices.length ≤ 3 · 10⁴
- 0 ≤ prices[i] ≤ 10⁴
- At most one share at a time
Edge cases to test
- Prices only fall:
0 - Flat prices
- One day
Follow-up questions
- Why is summing every rise optimal?
- Any trade from day i to j earns the sum of the daily rises between them, so taking every positive rise is at least as good as any set of trades.
- What if each trade costs a fee?
- A hold / not-hold DP:
hold = max(hold, cash − p),cash = max(cash, hold + p − fee)(LC 714). O(n), O(1).
Solution
Java
public int maxProfit(int[] prices) {
int profit = 0;
for (int i = 1; i < prices.length; i++) {
int rise = prices[i] - prices[i - 1];
if (rise > 0) profit += rise;
}
return profit;
}Python
def max_profit(prices):
profit = 0
for i in range(1, len(prices)):
rise = prices[i] - prices[i - 1]
profit += max(rise, 0)
return profitC++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int maxProfit(vector<int> &prices) {
int profit = 0;
for (int i = 1; i < int(prices.size()); i++) {
int rise = prices[i] - prices[i - 1];
if (rise > 0) profit += rise;
}
return profit;
}
};
More Greedy problems
- Maximum Subarray (Medium)
- Jump Game (Medium)
- Jump Game II (Medium)
- Gas Station (Medium)
- Partition Labels (Medium)
- Task Scheduler (Medium)
- Hand of Straights (Medium)
- Merge Triplets to Form Target Triplet (Medium)
- Valid Parenthesis String (Medium)
- Minimum Number of Arrows to Burst Balloons (Medium)
- Candy (Hard)
- Boats to Save People (Medium)
- Two City Scheduling (Medium)