Best Time to Buy and Sell

You are given an array(PRICES) of stock prices for N consecutive days. Your task is to find the maximum profit that you can make by completing as many transactions as you like, where a transaction denotes buying one and selling one share of the stock.

Note:

You must sell the stock before you buy it again.
Input Format:
The first line of input contains an integer value N, denoting the size of the input array.

The second line contains N single space-separated integers, denoting the prices on each day.
Output Format:
The only output line contains an integer, denoting the maximum profit.

Note:

You are not required to print the output, it has already been taken care of. Just implement the function. 
Constraints:
1 <= N <= 5 * 10^4
0 <= PRICES[i] <= 10^4    

Time Limit: 1sec
CodingNinjas
author
2y

Initially I used many techniques but was not able to get satisfactory results. Then I used the dynamic programming approach to solve this.

CodingNinjas
author
2y
Recursive Approach

In this approach, we will be using recursion, where we will have a recursive method let's say MAX_PROFIT(PRICES, START) to find the maximum profit that we can make by doing any numbe...read more

CodingNinjas
author
2y
Memoization Approach

In this approach, we will be using recursion, where we will have a recursive method let's say MAX_PROFIT(PRICES, START) to find the maximum profit that we can make by doing any num...read more

CodingNinjas
author
2y
Peaks and Troughs

To calculate the maximum profit, we will first plot the graph where the x-axis will denote the indexes and the y-axis will denote the prices. We should buy the stock at the first trou...read more

CodingNinjas
author
2y
Positive Slopes Contribution

To calculate the maximum profit, we will first plot the graph where the x-axis will denote the indexes and the y-axis will denote the prices. Now if you carefully observe t...read more

Add answer anonymously...
UnitedHealth Software Developer Intern Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions
Get AmbitionBox app

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter