FastPrepMaximum Profit from Selling Before Buying
Problems/Maximum Profit from Selling Before Buying

Maximum Profit from Selling Before Buying

AMD logoAMD● EasyFULLTIMEONSITE INTERVIEW
QuestionFunctionExamplesConstraints

Problem statement

Source note: The report specifies selling first and buying later but omits the trading rules. This exercise allows one unit, at most one transaction, strictly later repurchase, no fees and an optional zero-profit outcome.

Given daily stock prices prices, you may make at most one transaction: sell one unit on day i, then buy it back on a strictly later day j.

The profit is prices[i] - prices[j]. Return the maximum profit, or 0 if making no transaction is better. There are no fees or other costs.

Function

maximumShortProfit(prices: int[]) → int

Examples

Example 1

prices = [8,4,6,2]return = 6

Sell at 8 on day 0 and buy at 2 on day 3, for a profit of 6.

Example 2

prices = [1,2,3]return = 0

Every later buy costs more than the earlier sale. Making no transaction yields 0.

Constraints

  • 0 <= prices.length <= 100000.
  • 0 <= prices[i] <= 1000000000.

More AMD problems

  • Insert After a Linked-List NodeONSITE INTERVIEW · Seen Oct 2026
  • LRU CacheONSITE INTERVIEW · Seen Oct 2026
  • Lowest Common Ancestor of a Binary TreePHONE SCREEN · Seen Oct 2026
All AMD interview questionsSee AMD hiring insights
Saved
public int maximumShortProfit(int[] prices) {
    // Write your code here.
}
Checking account…