Day 1 (Stock Buy and Sell Problem)

Leetcode 121

ยท

3 min read

Greetings fellow adventurers in the realm of competitive programming! Today marks the beginning of my epic journey into the world of algorithms, data structures, and the legendary LeetCode.

We are solving our very first intersting challenge: the notorious "Best Time to Buy and Sell Stock" problem.

Ah, the whimsical world of stocks and investments! Who knew that my quest for coding prowess would lead me to dabble in the realm of Wall Street? But fear not, for I am armed with wit, determination, and a trusty compiler at my side.

Problem statement

You are given an array prices where prices[i] is the price of a given stock on the i<sup>th</sup> day.

You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.

Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.

Example 1:

Input: prices = [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.

Example 2:

Input: prices = [7,6,4,3,1]
Output: 0
Explanation: In this case, no transactions are done and the max profit = 0.

Disclamimer: If you didn't understand the code or logic just read it again.

Logic of the problem

We scrutinize each price. If we encounter a price lower than the current minimum, we update our minimum price. However, if the price is higher, we calculate the potential profit by subtracting the minimum price from the current price. We then compare this profit with the maximum profit we've amassed thus far, keeping the greater of the two.

Code:

#include <iostream>             // Including the input-output stream library
#include <algorithm>            // Including the algorithm library for using 
                                //the max function

using namespace std;            
                               /* Function to find the maximum profit from buying 
                                   and selling stocks*/
int maxProfit(int prices[], int n) {
    if (n == 0) return 0;        // If there are no prices, return 0

    int max_profit = 0; // Initialize the maximum profit to 0
    int min_price = prices[0];    /* Initialize the minimum price to the 
                                  first price in the array*/

    // Loop through the prices array starting from the second price
    for (int i = 1; i < n; ++i) {
                                    /*If the current price is less than 
                                    the minimum price encountered so far*/
        if (prices[i] < min_price) {
            min_price = prices[i]; // Update the minimum price
        } else {                   /* If the current price is greater than or 
                                    equal to the minimum price*/
                                   /* Calculate the profit by selling at the 
                                   current price and buying at the minimum price*/
            max_profit = max(max_profit, prices[i] - min_price);
        }
    }

    return max_profit;           
}

int main() {
    int prices[] = {7, 1, 5, 3, 6, 4}; // Sample prices array
    int n = sizeof(prices) / sizeof(prices[0]); 
               // Calculate the number of elements in the prices array

    int max_profit = maxProfit(prices, n); 
               // Call the maxProfit function to find the maximum profit

    cout << "Max Profit: " << max_profit << endl; // Output the maximum profit
    return 0; 
}

And there you have it, brave souls! With a stroke of my coding logic and a dash of algorithmic sorcery, we have emerged victorious in our quest to conquer the Stock Buy and Sell problem. But fear not, for our journey has only just begun. Try to understand and execute this code in your favourite IDE.

Stay tuned for next more epic adventures in the realm of competitive programming! Happy coding ๐Ÿš€โœจ

ย