Why my C++ solution with O(nk) time gets TLE??


  • 0
    Z
    int maxProfit(int k, vector<int>& prices) {
        int ret = 0;
        int prices_size = prices.size();
        vector<int> f(prices_size, 0);
        int loop_end = (prices_size < k)?prices_size:k;
        for (int j = 1; j <= loop_end; ++j) {
            int maxx = -prices[0];
            for (int i = 0; i < prices_size; ++i) {
                int p = (i+1<prices_size)?(f[i] - prices[i+1]):INT_MIN;
                f[i] = max(f[i-1], maxx + prices[i]); 
                maxx = max(maxx, p); 
            }
        }
        for (int i = 0; i < prices_size; ++i) {
            ret = max(ret, f[i]);
        }
        return ret;
    }
    

    I saw a lot of other solutions with O(nk) time get accept, why my solution gets TLE???
    Can anyone help???


Log in to reply
 

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