Stock Buy Sell to Maximize Profit in c#

To solve the problem of maximizing profit from stock buy and sell operations in C#, you can use a simple algorithm that iterates through the prices of the stock, keeping track of the minimum price encountered so far and calculating the potential profit at each step.

Algorithm Explanation

  1. Initialization: Start by initializing two variables: one for tracking the minimum price and another for tracking the maximum profit.

  2. Iterate Through Prices: Loop through the array of stock prices:

    • For each price, check if it is less than the current minimum price. If it is, update the minimum price.
    • Calculate the profit if you were to sell at the current price (current price - minimum price).
    • If the calculated profit is greater than the current maximum profit, update the maximum profit.
  3. Return the Result: After looping through all the prices, the maximum profit variable will hold the highest profit possible from one buy-sell operation.

C# Implementation

Here’s a sample implementation of the above algorithm:

using System;

class Program
{
    static void Main()
    {
        int[] prices = { 7, 1, 5, 3, 6, 4 };
        int maxProfit = MaxProfit(prices);
        Console.WriteLine("Maximum Profit: " + maxProfit);
    }

    static int MaxProfit(int[] prices)
    {
        if (prices.Length == 0) return 0;

        int minPrice = prices[0];
        int maxProfit = 0;

        for (int i = 1; i < prices.Length; i++)
        {
            // Update minimum price if current price is lower
            if (prices[i] < minPrice)
            {
                minPrice = prices[i];
            }
            // Calculate profit if selling at current price
            int profit = prices[i] - minPrice;

            // Update maximum profit if the calculated profit is higher
            if (profit > maxProfit)
            {
                maxProfit = profit;
            }
        }

        return maxProfit;
    }
}

Explanation of Code

  1. Input: An array of integers (prices) representing the stock prices on different days.
  2. MaxProfit Function: This function calculates the maximum profit that can be obtained by buying and selling the stock once.
    • It first checks if the prices array is empty; if it is, it returns 0 (no profit can be made).
    • It initializes minPrice with the first day’s price and maxProfit to 0.
  3. Looping Through Prices: The for loop starts from the second element (index 1) and does the following:
    • If the current price is lower than the minPrice, it updates minPrice.
    • It calculates the potential profit by subtracting minPrice from the current price.
    • If the calculated profit is greater than the maxProfit, it updates maxProfit.
  4. Return the Result: After checking all prices, the function returns the maximum profit.

Complexity

  • Time Complexity: O(n), where n is the number of prices. You only loop through the array once.
  • Space Complexity: O(1), as you are using a fixed number of variables regardless of input size.

This method ensures that you find the best possible buy-sell pair to maximize profit efficiently.