Quick Overview

Given daily stock prices, return the largest profit obtainable from at most one purchase followed by one later sale, or zero when no profitable trade exists.

Find the Best Profit from One Stock Trade

Company: Oracle

Role: Backend Engineer

Category: Coding & Algorithms

Difficulty: medium

Interview Round: Onsite

## Problem Given daily stock prices, choose at most one buy followed by at most one sell and return the maximum possible profit. The sale must occur on a later day than the purchase. Return `0` when no profitable trade exists. ### Function Contract Implement `maxSingleTradeProfit(prices)` and return one integer. ### Constraints & Assumptions - `0 <= len(prices) <= 200,000`. - `0 <= prices[i] <= 10^9`. - You may hold at most one share. - Transaction fees and taxes are ignored. ### Clarifying Questions to Ask - May the stock be sold before it is bought? No. - Is doing nothing allowed? Yes, yielding profit `0`. - Are multiple transactions allowed? No. ```hint Keep the best purchase seen so far While scanning from left to right, compare today's price with the minimum earlier price, then update the minimum for future days. ``` ### Examples ```text [7,1,5,3,6,4] -> 5 [7,6,4,3,1] -> 0 [2,4,1] -> 2 ``` ### Evaluation Focus - Preserves buy-before-sell order. - Returns zero for descending, empty, or single-price inputs. - Runs in `O(n)` time and `O(1)` auxiliary space. ### Extensions to Discuss 1. How would you return the buy and sell indices? 2. What changes if unlimited nonoverlapping transactions are allowed? 3. How would a transaction fee affect the state?

Overview: Given daily stock prices, return the largest profit obtainable from at most one purchase followed by one later sale, or zero when no profitable trade exists.

Read the full Oracle Backend Engineer interview experience this question came from

Given daily nonnegative stock prices, choose at most one buy and one later sell. Return the maximum profit, or zero if no profitable trade exists.

Constraints

  • 0 <= len(prices) <= 200000.
  • 0 <= prices[i] <= 1000000000.
  • The sell day must be later than the buy day.
  • Doing nothing yields zero.

Examples

Input: ([7, 1, 5, 3, 6, 4],)

Expected Output: 5

Explanation: Buy at one and sell at six.

Input: ([7, 6, 4, 3, 1],)

Expected Output: 0

Explanation: A descending series has no profitable trade.

Hints

  1. Maintain the cheapest purchase seen so far.
  2. Never allow a later minimum to serve as an earlier buy for the same day.

Loading coding console...