LeetCode: Best Time to Buy and Sell Stock Solution in C

You are given an array of prices where prices[i] is the price of a given stock on an ith 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.

int max(int num1, int num2){
    return num1>num2?num1:num2;
}

int min(int num1, int num2){
    return num1>num2?num2:num1;
}

int maxProfit(int* prices, int pricesSize){
    int buy_price = INT_MAX, profit = 0;
    for(int i=0; i<pricesSize; i++){
        buy_price = min(buy_price, prices[i]);
        profit = max(profit, prices[i]-buy_price);        
        }
    return profit;
}

Leave a Comment