Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Best Stock Profit Calculation

EasyPython00:00
Practice interviewer
In session
5 left
00:00

Your question is Best Stock Profit Calculation. Start with the requirements on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

A First Citizens BancShares market-monitoring component receives daily closing prices for a stock. Given the prices in chronological order, determine the maximum profit possible from exactly one purchase and one sale.

You must buy on one day and sell on a later day. If no profitable transaction is possible, return 0. Do not reorder the prices or perform multiple transactions.

Formal Specification

Implement max_profit(prices).

  • Input: prices, a list of integers where prices[i] is the stock's closing price on day i.
  • Output: An integer representing the largest possible profit, calculated as sell_price - buy_price.
  • The transaction must satisfy buy_day < sell_day.

Constraints

  • 0 <= prices.length <= 10^5
  • 0 <= prices[i] <= 10^9
  • At most one buy and one later sell are allowed
  • Return 0 when no positive profit is possible

Function Signature

def max_profit(prices):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output