Why my O(2k) space solution "Memory Limit Exceeded"?


  • 0
    E

    The posted answers seems use O(nk) space, but my below solution only has O(2k) got Memory Limit Exceeded, Any ideas? Thanks.

    public int maxProfit(int k, int[] prices) {
            int n = 2*k;
            int[] m = new int[n];
            for(int j = 0; j < prices.length; j++) {
                for(int i = 0; i < 2*k; i++) {
                    int sign = 2*(i%2) - 1;
                    int a = (i > 0 ? m[i-1]:0) + sign*prices[j];
                   	m[i] = j > 0 ? Math.max(m[i], a) : a;
                }
            }
            int res = 0;
            for(int i = 0; i < n; i++) {
                if(i%2 == 1) {
                    res = Math.max(m[i], res);
                }
            }
            return res;
        }
    

Log in to reply
 

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