FastPrepMaximum Stock Profit with Unlimited Transactions
Problem · Array

Maximum Stock Profit with Unlimited Transactions

Learn this problem
MediumSalesforce logoSalesforceNEW GRADONSITE INTERVIEW
See Salesforce hiring insights

Problem 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[]) → long

Examples

Example 1

prices = [7,1,5,3,6,4]return = 7

Buy at 1 and sell at 5, then buy at 3 and sell at 6.

Example 2

prices = [1,2,3,4,5]return = 4

Holding across the increasing run earns 5 - 1 = 4.

Example 3

prices = [7,6,4,3,1]return = 0

Every 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.

More Salesforce problems

drafts saved locally
public long maxProfitUnlimited(int[] prices) {
    // Write your code here.
}
prices[7,1,5,3,6,4]
expected7
checking account