Binary TreesBinary Trees36

  1. 1Preorder Traversal of a Binary Tree using Recursion
  2. 2Preorder Traversal of a Binary Tree using Iteration
  3. 3Postorder Traversal of a Binary Tree Using Recursion
  4. 4Postorder Traversal of a Binary Tree using Iteration
  5. 5Level Order Traversal of a Binary Tree using Recursion
  6. 6Level Order Traversal of a Binary Tree using Iteration
  7. 7Reverse Level Order Traversal of a Binary Tree using Iteration
  8. 8Reverse Level Order Traversal of a Binary Tree using Recursion
  9. 9Find Height of a Binary Tree
  10. 10Find Diameter of a Binary Tree
  11. 11Find Mirror of a Binary Tree - Todo
  12. 12Inorder Traversal of a Binary Tree using Recursion
  13. 13Inorder Traversal of a Binary Tree using Iteration
  14. 14Left View of a Binary Tree
  15. 15Right View of a Binary Tree
  16. 16Top View of a Binary Tree
  17. 17Bottom View of a Binary Tree
  18. 18Zigzag Traversal of a Binary Tree
  19. 19Check if a Binary Tree is Balanced
  20. 20Diagonal Traversal of a Binary Tree
  21. 21Boundary Traversal of a Binary Tree
  22. 22Construct a Binary Tree from a String with Bracket Representation
  23. 23Convert a Binary Tree into a Doubly Linked List
  24. 24Convert a Binary Tree into a Sum Tree
  25. 25Find Minimum Swaps Required to Convert a Binary Tree into a BST
  26. 26Check if a Binary Tree is a Sum Tree
  27. 27Check if All Leaf Nodes are at the Same Level in a Binary Tree
  28. 28Lowest Common Ancestor (LCA) in a Binary Tree
  29. 29Solve the Tree Isomorphism Problem
  30. 30Check if a Binary Tree Contains Duplicate Subtrees of Size 2 or More
  31. 31Check if Two Binary Trees are Mirror Images
  32. 32Calculate the Sum of Nodes on the Longest Path from Root to Leaf in a Binary Tree
  33. 33Print All Paths in a Binary Tree with a Given Sum
  34. 34Find the Distance Between Two Nodes in a Binary Tree
  35. 35Find the kth Ancestor of a Node in a Binary Tree
  36. 36Find All Duplicate Subtrees in a Binary Tree

Stock Buy and Sell
Optimal Solution using Single Pass



Problem Statement

Given an array prices, where prices[i] represents the stock price on the ith day, your task is to find the maximum profit you can achieve by choosing a single day to buy one stock and a different day in the future to sell that stock.

Examples

Input PricesMaximum ProfitDescription
[7, 1, 5, 3, 6, 4]5Buy at 1 and sell at 6 (6 - 1 = 5)
[7, 6, 4, 3, 1]0Prices continuously decline — no profit is possible
[1, 2, 3, 4, 5]4Buy at 1 and sell at 5 — increasing prices
[2, 4, 1, 5]4Buy at 1 and sell at 5
[5]0Only one price — no possible transaction
[]0Empty array — no data to work with

Solution

To solve this problem, we need to find the best possible pair of days to buy and then sell a stock to maximize our profit. But we are allowed to do this only once — that is, we can make one buy and one sell, and the buy must happen before the sell.

The trick is to look at the prices and figure out how low we can buy and how high we can sell after that buy. So, we keep track of the minimum price we’ve seen so far while scanning the array, and at each step, we check if selling at the current price would give us more profit than what we’ve recorded before.

Understanding Through Cases

  • Case 1: Profitable Transaction Exists
    If the prices go up after some point, we can buy at the low point and sell at the high point. For example, in [7, 1, 5, 3, 6, 4], we buy at 1 and sell at 6 to gain a profit of 5.
  • Case 2: Prices Only Go Down
    If the prices keep decreasing (like [7, 6, 4, 3, 1]), then no matter where we buy and sell, we’ll always lose money. In such cases, the best we can do is avoid any transaction, and the answer is 0.
  • Case 3: Constant or Increasing Trend
    When prices steadily increase (like [1, 2, 3, 4, 5]), we can buy at the very beginning and sell at the end. This gives us the highest possible profit in the trend.
  • Case 4: Only One Price
    If the array has only one price, we cannot sell after buying, so no profit can be made. Hence, the answer is 0.
  • Case 5: Empty Input
    If the prices array is empty, there is no transaction possible at all. So, we return 0.

This method works efficiently because we only need to pass through the array once while tracking the lowest price seen so far and the best profit we can get. That gives us a time complexity of O(n), which is optimal for this problem.

Visualization

Algorithm Steps

  1. Given an array prices where prices[i] represents the price of a stock on the ith day.
  2. Initialize min_price to a very large number and max_profit to 0.
  3. Traverse through the array:
  4. → If prices[i] is less than min_price, update min_price.
  5. → Else, calculate the profit by prices[i] - min_price and update max_profit if it is greater.
  6. After the loop, return max_profit.

Code

Python
JavaScript
Java
C++
C
def max_profit(prices):
    min_price = float('inf')
    max_profit = 0
    for price in prices:
        if price < min_price:
            min_price = price
        elif price - min_price > max_profit:
            max_profit = price - min_price
    return max_profit

# Sample Input
prices = [7, 1, 5, 3, 6, 4]
print("Max Profit:", max_profit(prices))

Time Complexity

CaseTime ComplexityExplanation
Best CaseO(n)Even in the best case (increasing prices), the algorithm must scan all elements to compute maximum profit.
Average CaseO(n)The algorithm performs a single pass over the array to track the minimum price and compute the maximum profit.
Average CaseO(n)In the worst case (decreasing prices), the algorithm still traverses the entire array to ensure no profit is possible.

Space Complexity

O(1)

Explanation: The solution uses a constant amount of extra space, maintaining only variables like min_price and max_profit.



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M