ADS
Algorithms and Data Structures
Loading...
Searching...
No Matches
StockTrading.h File Reference

The largest gain of buying and selling a stock with at most \( k \), or with exactly \( k \), transactions, given its prices on \( n \) days: a transaction buys on a day \( b \) and sells on a later day \( s \), and the transactions do not overlap, \( b_1 < s_1 < b_2 < s_2 < \cdots < b_k < s_k \). More...

#include "ADS/Contract.h"
#include <algorithm>
#include <cstddef>
#include <optional>
#include <vector>
#include "ADS/optimization/impl/StockTrading.tpp"

Go to the source code of this file.

Namespaces

namespace  ADS

Functions

template<class T>
T ADS::maxProfit (const std::vector< T > &prices, std::size_t k)
 the largest gain of at most \( k \) transactions on the prices
template<class T>
std::optional< T > ADS::maxProfitExactly (const std::vector< T > &prices, std::size_t k)
 the largest gain of exactly \( k \) transactions on the prices, nothing if there are fewer than \( 2 k \) days

Detailed description

The largest gain of buying and selling a stock with at most \( k \), or with exactly \( k \), transactions, given its prices on \( n \) days: a transaction buys on a day \( b \) and sells on a later day \( s \), and the transactions do not overlap, \( b_1 < s_1 < b_2 < s_2 < \cdots < b_k < s_k \).

The dynamic programming scans the days keeping, for each \( l \le k \), the best balance \( \mathit{free}[ l ] \) with \( l \) transactions closed and no stock, and the best balance \( \mathit{hold}[ l ] \) with the stock of the \( l \)-th transaction in hand: on the day of price \( x \), \( \mathit{free}[ l ] = \max( \mathit{free}[ l ] , \mathit{hold}[ l ] + x ) \) and \( \mathit{hold}[ l ] = \max( \mathit{hold}[ l ] , \mathit{free}[ l - 1 ] - x ) \), each from the values of the days before (\( l \) going down), which keeps the days distinct; \( O( n k ) \) time and \( O( k ) \) space. The text of the exercise writes the \( O( k n^2 ) \) table on the day of the last sale.

With at most \( k \) transactions the answer is not negative, and for \( k \ge n / 2 \) it is the sum of the positive differences of consecutive prices, \( O( n ) \); with exactly \( k \) the answer may be negative, and there is none for \( n < 2 k \). The case \( k = 1 \) is the largest difference \( x_s - x_b \), \( s > b \), which is the maximum sum segment of the differences [see MaximumSegments.h].

The contracts [see Contract.h]: the gain of at most \( k \) transactions is not negative. The functions are defined in StockTrading.tpp.

See also
A. Montresor, Algoritmi e Strutture Dati, 2025, chapter 13 and the Esercizi Programmazione dinamica, exercise B3 of 12/01/2026, https://algoritmicamente.it/materiali/libro/capitoli/cap13.pdf
J. Bentley, Programming Pearls, 2nd ed., Addison-Wesley, 2000, column 8
Author
Donato Meoli
Dipartimento di Informatica
Università di Pisa