Java heap space

  • 0

    Here is my code for Best Time to Buy and Sell Stock IV (extend to allow at most k transactions). I got following error when k is 1000000000
    Line 3: java.lang.OutOfMemoryError: Java heap space

    Is there any suggestion to avoid this problem please? Thanks.

    public class Solution {
        public int maxProfit(int k, int[] prices) {
            int[] sell = new int[k+1];
            int[] buy = new int[k+1];
            Arrays.fill(buy, Integer.MIN_VALUE);
            for (int i:prices)
                for (int j=k; j>0; j--)
                    sell[j] = Math.max(sell[j], buy[j]+i);
                    buy[j] = Math.max(buy[j], sell[j-1]-i);
            return sell[k];

Log in to reply

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