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

Edge cases to test

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 profit

C++

#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