Problem · Dynamic Programming
Count Bounded Share Transactions
Learn this problemProblem statement
You start with startShares shares. One transaction does exactly one of the following:
- buy one share, increasing the holding by one; or
- sell one share, decreasing the holding by one, provided the holding is positive before the sale.
Count all distinct transaction sequences whose length is between 0 and maxTransactions, inclusive, and that finish with exactly targetShares shares. The empty sequence counts when the starting and target holdings are equal.
Return the total number of valid sequences.
Function
countTransactionSequences(startShares: int, targetShares: int, maxTransactions: int) → longExamples
Example 1
startShares = 1targetShares = 2maxTransactions = 3return = 4One one-transaction sequence and three three-transaction sequences finish at two shares: B, BBS, BSB, and SBB.
Example 2
startShares = 0targetShares = 0maxTransactions = 2return = 2The empty sequence and BS are valid. A sequence cannot begin with a sale at zero shares.
Constraints
0 <= startShares <= 600 <= targetShares <= 600 <= maxTransactions <= 60- The answer fits in a signed 64-bit integer.