Problem · Array
Maximum Stock Profit with Unlimited Transactions
Learn this problemProblem statement
Given prices, where prices[i] is one share's price on day i, return the maximum profit obtainable.
For this exercise, assume you may complete any number of buy-then-sell transactions, may hold at most one share, and must sell before buying again. You may also make no transaction.
Function
maxProfitUnlimited(prices: int[]) → longExamples
Example 1
prices = [7,1,5,3,6,4]return = 7Buy at 1 and sell at 5, then buy at 3 and sell at 6.
Example 2
prices = [1,2,3,4,5]return = 4Holding across the increasing run earns 5 - 1 = 4.
Example 3
prices = [7,6,4,3,1]return = 0Every sale would lose money, so make no transaction.
Constraints
1 <= prices.length <= 10^5.0 <= prices[i] <= 10^5.- The answer fits in a signed 64-bit integer.