VOOZH about

URL: https://www.geeksforgeeks.org/dsa/c-program-for-stock-buy-sell-to-maximize-profit-2/

⇱ C Program For Stock Buy Sell To Maximize Profit - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

C Program For Stock Buy Sell To Maximize Profit

Last Updated : 23 Jul, 2025

Efficient approach: If we are allowed to buy and sell only once, then we can use following algorithm. Maximum difference between two elements. Here we are allowed to buy and sell multiple times. 
Following is the algorithm for this problem.  

  1. Find the local minima and store it as starting index. If not exists, return.
  2. Find the local maxima. and store it as an ending index. If we reach the end, set the end as the ending index.
  3. Update the solution (Increment count of buy-sell pairs)
  4. Repeat the above steps if the end is not reached.

Output:

Buy on day: 0 Sell on day: 3
Buy on day: 4 Sell on day: 6

Time Complexity: The outer loop runs till I become n-1. The inner two loops increment value of I in every iteration. So overall time complexity is O(n)

Auxiliary Space: O(1) since using constant variables

Please refer complete article on Stock Buy Sell to Maximize Profit for more details!

Comment