Best time to buy and sell stock II

You have been given stock values/prices for N number of days. Every i-th day signifies the price of a stock on that day. Your task is to find the maximum profit which you can make by buying and selling the stocks.

 Note :
You may make as many transactions as you want but can not have more than one transaction at a time i.e, if you have the stock, you need to sell it first, and then only you can buy it again.
Input format :
The first line contains an integer 't' which denotes the number of test cases or queries to be run. Then the test cases follow.

The first line of each test case or query contains an integer 'N' representing the total number of days for which you have stock prices.

The second line contains 'N' single space-separated integers representing the price of the stock on i-th day.
Output Format :
For each test case, print the maximum profit that you can earn.

Output for every test case will be printed in a separate line.
Note :
You are not required to print anything explicitly. Just implement the function.
Constraints :
1 <= t <= 10^2
0 <= N <= 10^5
Time Limit: 1 sec
CodingNinjas
author
2y

Used Dynammic Programming for it.

CodingNinjas
author
2y
Brute Force Approach

Let's say we have stock values of two days, say, [20, 30].

One must have to buy the stock first in order to sell it in the coming days.

So,

1. if I choose to buy the stock on first d...read more

CodingNinjas
author
2y
Local Minima/Maxima Approach
  1. Keep a ‘profit’ variable to keep track of the total profit earned
  2. Check the stock prices of every two consecutive days with a loop
    1. If the price on the second day is more than...read more
Add answer anonymously...
Clarivate Associate Software Engineer 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