Maximize Stock Trading Profit

You are given an array prices, representing stock prices over N consecutive days. Your goal is to compute the maximum profit achievable by performing multiple transactions (i.e., buying one share and then selling one share multiple times).

Note: You must sell a stock before buying again.

Input:

N  
prices[0] prices[1] ... prices[N-1]

Output:

maximum_profit

Example:

Input:
6  
7 1 5 3 6 4
Output:
7
Explanation:

The maximum profit can be achieved by buying on day 2 (at price 1) and selling on day 3 (at price 5), profit = 5-1 = 4. Then buying again on day 4 (at price 3) and selling on day 5 (at price 6), profit = 6-3 = 3. Total profit is 4 + 3 = 7.

Constraints:

  • 1 <= N <= 5 * 104
  • 0 <= prices[i] <= 104
  • Time Limit: 1 second
Be the first one to answer
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

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