Link Search Menu Expand Document

121. Best Time to Buy and Sell Stock

Solution Code

C

int maxProfit(int* prices, int pricesSize){
    int answer = 0;
    int buyingPrice = prices[0];
    
    for (int i = 1; i < pricesSize; i++){
        if (prices[i] < buyingPrice)
            buyingPrice = prices[i];
        else if (prices[i] - buyingPrice > answer)
            answer = prices[i] - buyingPrice;
    }
    
    return answer;
}

© 2023. All rights reserved.