1 / 3
Jan 2020

I am getting NZEC runtime error while the code runs on my computer for the problem : https://www.spoj.com/problems/COINS/4
I have written this code:
package com.dynamic.programming;

import java.util.Scanner;

public class Main {

public static int dp[];
public static void main(String[] args) {
	// TODO Auto-generated method stub
	Scanner sc = new Scanner(System.in);
	int n = 0;
	
	while(sc.hasNextInt()) {
		n = sc.nextInt();
		if(n<=99999998) {
			dp = new int[n+1];
		for(int i=0;i<=n;i++)
			dp[i] = -1;
		}else {
			dp = new int[99999999];
		}
		System.out.println(coins(n));
	}
}

public static int coins(int n) {
	if(n<=5)
		return n;
	if(n<=99999998) {
	if(dp[n] != -1)
		return dp[n];
	dp[n] = Math.max(coins(n/2) + coins(n/3) + coins(n/4),n);
	return dp[n];
	}
	else return Math.max(coins(n/2) + coins(n/3) + coins(n/4),n);
}

}

  • created

    Jan '20
  • last reply

    Jan '20
  • 2

    replies

  • 752

    views

  • 2

    users

  • 1

    link

When I ran it on IDEONE, it gave the exception

Exception in thread “main” java.lang.OutOfMemoryError: Java heap space
at Main.main(Main.java:18)

A hint… I only memoised part of the range, and used recursion for the rest of it.

A question… why do you create a new DP cache with each test case? Will the numbers stored in DP change between cases?

Suggested Topics

Want to read more? Browse other topics in JAVA based languages or view latest topics.