Best Time to Buy and Sell Stock II - C Solution

1. Introduction

In this post, we explore a variation of the stock buying and selling problem: "Best Time to Buy and Sell Stock II". Unlike the previous version where only one transaction was allowed, this problem allows multiple transactions to maximize profit. This scenario is common in trading algorithms and financial software development, where understanding optimal buy-sell strategies is crucial.

Problem

Given an integer array prices where prices[i] is the price of a given stock on the ith day, the goal is to find the maximum profit achievable through multiple transactions. You may buy and sell the stock on the same day, but you can only hold at most one share at a time.

2. Solution Steps

1. Initialize a variable maxProfit to keep track of the total profit.

2. Iterate through the array, starting from the first day.

3. For each day, if the price of the stock is higher than the previous day, add the difference to maxProfit.

4. Continue this process until the end of the array.

5. Return the total maxProfit.

3. Code Program

#include <stdio.h>

// Function to calculate the maximum profit
int maxProfit(int* prices, int pricesSize) {
    int maxProfit = 0; // Initialize maxProfit as 0

    // Loop through each day, starting from the second day
    for (int i = 1; i < pricesSize; i++) {
        // If today's price is higher than yesterday's, add the difference to maxProfit
        if (prices[i] > prices[i - 1]) {
            maxProfit += prices[i] - prices[i - 1];
        }
    }
    return maxProfit; // Return the total profit
}

// Main function to test the maxProfit function
int main() {
    int prices1[] = {7, 1, 5, 3, 6, 4};
    int pricesSize1 = sizeof(prices1) / sizeof(prices1[0]);
    printf("Maximum Profit (Example 1): %d\n", maxProfit(prices1, pricesSize1));

    int prices2[] = {1, 2, 3, 4, 5};
    int pricesSize2 = sizeof(prices2) / sizeof(prices2[0]);
    printf("Maximum Profit (Example 2): %d\n", maxProfit(prices2, pricesSize2));

    int prices3[] = {7, 6, 4, 3, 1};
    int pricesSize3 = sizeof(prices3) / sizeof(prices3[0]);
    printf("Maximum Profit (Example 3): %d\n", maxProfit(prices3, pricesSize3));

    return 0;
}

Output:

Maximum Profit (Example 1): 7
Maximum Profit (Example 2): 4
Maximum Profit (Example 3): 0

Explanation:

1. int maxProfit = 0; - Initialize maxProfit to zero.

2. for (int i = 1; i < pricesSize; i++) - Loop through each day, starting from day 2.

3. if (prices[i] > prices[i - 1]) - Check if today's price is higher than yesterday's.

4. maxProfit += prices[i] - prices[i - 1]; - If yes, add the difference to maxProfit.

5. return maxProfit; - Return the total profit made from all transactions.

6. The main function tests the maxProfit function with three different examples and prints the maximum profit for each.


Comments