Enrollments closing soon for Post Graduate Certificate Program in Applied Data Science & AI By IIT Roorkee | 3 Seats Left

  Apply Now

Data Structures and Algorithms Questions

2 / 13

Help Harshad with trading II

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 day to purchase a stock and choose another day in the future to sell that stock. He may complete as many trades as he likes (i.e., buy one and sell one share of the stock multiple times).

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.

Note: You must not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).

Example 1:

Input: prices = [7,1,5,3,6,4]
Output: 7
Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.

Example 2:

Input: prices = [1,2,3,4,5]
Output: 4
Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are engaging multiple transactions at the same time. You must sell before buying again.

Example 3:

Input: prices = [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e., max profit = 0.

Constraints:

  • 1 <= len(prices)<= 3 * 104
  • 0 <= prices[i] <= 104
INSTRUCTIONS

  1. Write your code inside a function named maximum_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' inside the block.
  5. Your code should work for all permitted possible values(check Constraints) of A and K

Complete the below code in the right side coding panel

def maximum_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...