Execution time difference


  • 0
    Y
        #include <limits>
    
    class Solution {
    public:
        int maxProfit(vector<int> &prices) {
            int n = prices.size();
            if ( n == 0 ) return 0;
            
            int max_profit = numeric_limits<int>::min();
            int min_price = numeric_limits<int>::max();
            
            for ( int i = 0; i < n ; ++i )
            {
                min_price = min(prices[i], min_price);
                max_profit = max(prices[i] - min_price, max_profit);
            }
            
            return max_profit;
        }
    };
    

    Above is my code, and the execution time is 24ms.

    if I change this line

    int max_profit = numeric_limits<int>::min();
    

    to

    int max_profit = 0;
    

    My execution time increases to 52ms. Anyone can explain this? Thank you!


  • 0
    S

    In general, there is no big difference between 24ms and 52ms. Anyhow, the common sense is calling a function always takes time compare to a constant value.


  • 0
    H

    Actually i tried ur code and got something different:
    with “numeric_limits<int>::min();” execution time is 60 ms
    replace it with "0", execution time is 52ms

    Additionally, i replace "0" with “numeric_limits<int>::min();” again and the execution time increases to 84 ms

    i googled about template coding, but got nothing helpful.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.