Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Max Profit From Prices

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

Your question is Max Profit From Prices. 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 monitoring component in Shift Technology's Force platform receives a sequence of daily values. Given an array of stock prices in chronological order, determine the maximum profit possible from one transaction: buy on exactly one day and sell on a later day. If no profitable transaction exists, return 0.

You must buy before selling, and each day can be used at most once. Return only the maximum profit, not the buy and sell indices.

Formal Specification

Implement max_profit(prices), where prices is a list of integers and prices[i] is the stock price on day i. Return an integer representing the greatest value of prices[j] - prices[i] for all pairs where i < j. Return 0 when every valid transaction loses money or when fewer than two prices are provided.

Constraints

  • 0 <= len(prices) <= 10^5
  • 0 <= prices[i] <= 10^4
  • At most one buy and one sell are allowed
  • The sell day must occur after the buy day

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