Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started
Dataford
Popular roles
Software EngineerData AnalystData ScientistData EngineerBusiness AnalystAI EngineerMachine Learning EngineerProduct Manager
Browse
Browse All RolesEvery role hub, from analyst to MLBrowse All CompaniesCompany-specific interview loopsAll Interview GuidesThe full guide library
Top questions by role
Software EngineerData AnalystData ScientistData EngineerBusiness AnalystAI EngineerMachine Learning EngineerProduct Manager
Top questions by skill
SQLPythonStatisticsMachine LearningA/B TestingSystem DesignGenerative AIProduct SenseMetricsBehavioral
Browse all questions →Try a mock interview
Experiences
Practice
Mock InterviewsTimed interview simulations with feedbackSuccess PathYour 6-week structured planModulesCurated lessons by topicWebinarsTalks from ex-Big Tech data leadsPlaygroundA free-form scratch editor
Learn
BlogInterview strategy and career adviceTech Job Market ReportHiring trends across data and AI rolesFor UniversitiesDataford for career centersAbout DatafordWho we are and how we build
Pricing
Build my plan
Best Time to Buy and Sell Stock I
00:00
5 left

Best Time to Buy and Sell Stock I

EasyPython

Problem

Best Time to Buy and Sell Stock (I).

Asked in the Coding round stage.

Given an array prices, where prices[i] is the stock price on day i, choose exactly one day to buy and a later day to sell. Return the maximum possible profit. Return 0 if no profitable transaction exists.

Function: def max_profit(prices):

Input: A non-empty list of integers. Output: An integer representing the maximum profit.

Example 1: prices = [7, 1, 5, 3, 6, 4] returns 5, by buying at 1 and selling at 6.

Example 2: prices = [7, 6, 4, 3, 1] returns 0, because prices continually decrease.

Constraints: 1 <= len(prices) <= 1000; 0 <= prices[i] <= 10^5.

Constraints

  • 1 <= len(prices) <= 1000
  • 0 <= prices[i] <= 10^5
  • Buy and sell at most once
  • The selling day must occur after the buying day

Function Signature

def max_profit(prices):
Interviewer

Your question is Best Time to Buy and Sell Stock I. Start with the requirements in the Question tab.

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.
CodePython 3
Sign up free to run your codeLog inLn 2
Run your code to see test output here.