Data Structures and Algorithms Questions

1 / 13

Help Harshad with trading I

Harshad is a newbie to trading, his boss gave him a long list of stock prices prices where prices[i] is the price of a stock on the ith day.

Harshad needs to maximize the profit by choosing a single day to purchase one stock and choose another day in the future to sell that stock.

Help Harshad by designing a function that will return the maximum possible profit that can be achieved by trading stocks as explained above, if there is no profit then return 0.

Examples:

Input: prices = [7,1,5,3,6,4] 
Output: 5
Explanation: Buy on day 2
(price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. Note
that buying on day 2 and selling on day 1 is not allowed because you
must buy before you sell.

Input: prices = [7,6,4,3,1]
Output: 0
Explanation: In this case, no transactions are done and the max profit = 0.

Constraints:

  • 1 <= prices.length <= 105
  • 0 <= prices[i] <= 104
INSTRUCTIONS

  1. Write your code inside a function named max_profit
  2. There are no partial marks for the question.
  3. Your function must return the output, it should not print the output.
  4. To execute a block on the right side coding panel, please press 'shift'+ 'enter'
  5. Your code should work for all permitted possible values(check Constraints) of prices

Complete the below code in the right side coding panel

def max_profit(prices: list) -> int:
    # your code goes here
See Answer

No hints are availble for this assesment


Note - Having trouble with the assessment engine? Follow the steps listed here

Loading comments...