FastPrepMost Money from One Stock Trade
Problems/Most Money from One Stock Trade

Most Money from One Stock Trade

Indeed logoIndeed● MediumNEW GRADOA
QuestionFunctionExamplesConstraints

Problem statement

Source note: This is a cash-based take on Best Time to Buy and Sell Stock I: one buy day, one later sell day, and as many shares as the money allows. The author's later reply gives an example with prices 4 10 6 7 1 5 and 100 dollars, and claims 250.

That example is not the best trade under the same rule. Buying 100 shares at 1 and selling them at 5 gives 500, so 500 is the judged answer here. The reply asks for the largest profit, while the first post asks for the most money at the end. This version returns the final amount of money, not the profit. The report does not say whether shares must be whole, what happens when no trade helps, or any limits. Here, you buy whole shares, keep the money you did not spend, and may skip trading. There are at most 2 * 10^4 days, and prices and cash are at most 10^9.

The judged task matches the report at about 85%.

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:

  1. 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.
  2. 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) → long

Examples

Example 1

prices = [4,10,6,7,1,5]cash = 100return = 500

Buying 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 = 30

The 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 = 50

The 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^4
  • 1 <= prices[i] <= 10^9
  • 1 <= cash <= 10^9

More Indeed problems

  • Insert into an Unrolled Linked ListPHONE SCREEN · ONSITE INTERVIEW · Seen Sep 2026
  • Course Completion OrderPHONE SCREEN · Seen May 2025
  • Recipes You Can PreparePHONE SCREEN · Seen May 2025
All Indeed interview questionsSee Indeed hiring insights
Saved
class Solution {
    public long maxFinalCash(int[] prices, int cash) {
        // Write your code here.
    }
}
Checking account…