Live Batches
Masterclasses
Menu
Free Courses
Account
Login / Sign Up

Stock buy and sell

Medium Acceptance 29.18% Points 30.00

You are given an array arr where each element represents the cost of a stock on a particular day. Your task is to determine the maximum possible profit you can achieve by buying and selling the stock multiple times.

Note:

  • You can only sell a stock that you have previously bought.
  • You cannot hold more than one stock at a time on any given day.
Examples
Example 1

Example 1

Input: arr[] = [10, 22, 5, 75, 65, 80]

Output: 97

Explanation: Buy the stock on day 0 and sell it on day 1 => 22 - 10 = 12. Buy the stock on day 2 and sell it on day 3 => 75 - 5 = 70. Buy the stock on day 4 and sell it on day 5 => 80 - 65 = 15. Maximum Profit = 12 + 70 + 15 = 97

Example 2

Example 2

Input: arr[] = [90, 80, 70, 60, 50]

Output: 0

Explanation: No transactions can be made as the stock prices are continuously falling. Therefore, the maximum profit is 0.

Hints
Hint 1
Expected Time Complexity: O(n)
Hint 2
Expected Auxiliary Space: O(n)
Constraints
  • 2 = arr.size() = 10^6
  • 0 = arr[i] = 10^6
Companies
Amazon Microsoft Samsung Walmart Oracle + 5 more
Topics
Array Dynamic Programming
Solution.cs C#JavaPythonC++Javascript

Unlock the code editor

Sign in to write, run, and submit your solution against the full test suite.

  • Run code against sample & hidden test cases
  • Save submissions and track your streak
  • Compare with editorial & community solutions