Practice › Dynamic Programming
Stock Trading with at Most K Transactions
Hard · Dynamic Programming · Asked at Amazon, Google, Microsoft, Goldman Sachs
price[i] is a stock’s price on day i. You may complete at most k transactions (a transaction is one buy followed later by one sell, and you hold at most one share at a time). Print the maximum total profit.
Input
First line: n k. Second line: the n prices.
Output
The maximum profit.
Constraints
- 1 ≤ n ≤ 1000
- 1 ≤ k ≤ 100
- 0 ≤ price[i] ≤ 1000
For each j = 1…k keep buy[j] = best balance after the j-th buy and sell[j] = best balance after the j-th sell. Each day: buy[j] = max(buy[j], sell[j − 1] − price), sell[j] = max(sell[j], buy[j] + price). If k ≥ n / 2 the limit does not matter.
Example 1
Input
3 2 2 4 1
Output
2
Example 2
Input
6 2 3 2 6 5 0 3
Output
7
Hints
- Track your balance after the j-th buy and after the j-th sell, for every j up to k.
- The j-th buy can only follow the (j − 1)-th sell.
- buy[j] = max(buy[j], sell[j − 1] − price); sell[j] = max(sell[j], buy[j] + price).
Approach
Initialise buy[j] = −∞ and sell[j] = 0. For each price, update j = 1…k in increasing order. sell[k] at the end is the best profit with at most k transactions (unused transactions simply leave sell[j] equal to sell[j − 1]). With n ≤ 1000 and k ≤ 100 this is 10^5 updates.
Complexity: O(n · k) time · O(k) space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, k;
cin >> n >> k;
vector<long long> p(n);
for (auto &x : p) cin >> x;
vector<long long> buy(k + 1, LLONG_MIN / 2), sell(k + 1, 0);
for (long long x : p)
for (int j = 1; j <= k; j++) {
buy[j] = max(buy[j], sell[j - 1] - x);
sell[j] = max(sell[j], buy[j] + x);
}
cout << sell[k] << "\n";
return 0;
}Python solution
import sys
data = list(map(int, sys.stdin.read().split()))
n, k = data[0], data[1]
p = data[2 : 2 + n]
NEG = float("-inf")
buy = [NEG] * (k + 1)
sell = [0] * (k + 1)
for x in p:
for j in range(1, k + 1):
b = sell[j - 1] - x
if b > buy[j]:
buy[j] = b
s = buy[j] + x
if s > sell[j]:
sell[j] = s
print(sell[k])Java solution
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
in.nextToken();
int n = (int) in.nval;
in.nextToken();
int k = (int) in.nval;
long[] p = new long[n];
for (int i = 0; i < n; i++) {
in.nextToken();
p[i] = (long) in.nval;
}
long[] buy = new long[k + 1], sell = new long[k + 1];
Arrays.fill(buy, Long.MIN_VALUE / 2);
for (long x : p)
for (int j = 1; j <= k; j++) {
buy[j] = Math.max(buy[j], sell[j - 1] - x);
sell[j] = Math.max(sell[j], buy[j] + x);
}
System.out.println(sell[k]);
}
}Solve Stock Trading with at Most K Transactions online · All practice problems