Most Money from One Stock Trade
Problem statement
You are given an array prices, where prices[i] is the price of one share of a stock on day i, and an amount of money cash.
You can trade at most once:
- On one day, buy any whole number of shares whose total price is at most
cash. The money you do not spend stays with you. - On a later day, sell all of those shares at that day's price.
You may also choose not to trade. Return the most money you can have at the end.
Function
maxFinalCash(prices: int[], cash: int) → longExamples
Example 1
prices = [4,10,6,7,1,5]cash = 100return = 500Buying 25 shares at 4 and selling them at 10 turns 100 into 250. Buying 100 shares at 1 on day 4 and selling them at 5 on day 5 does better: 100 * 5 = 500. No other pair beats that, so the answer is 500.
Example 2
prices = [6,12,1,3]cash = 10return = 30The biggest gain per share is buying at 6 and selling at 12, but 10 dollars buy only 1 share there: 4 + 12 = 16. Buying 10 shares at 1 and selling them at 3 gives 30. The answer is 30.
Example 3
prices = [9,7,7,2]cash = 50return = 50The price never goes up after any day, so every trade loses money or breaks even. Keep the cash. The answer is 50.
Constraints
1 <= prices.length <= 2 * 10^41 <= prices[i] <= 10^91 <= cash <= 10^9