We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Hi! Thanks a lot for the great idea! I tried to implement based on your idea!
I tried to reimplement with Java, but still got timeout error :(
I guess problem is because I am looping several times through nums array ? (e.g. Initialize array part..)
It would be really helpful if someone help me out! Thanks a lot for help in advance :)
/*
* Complete the downToZero function below.
*/
static int downToZero(int n) {
/*
* Write your code here.
*/
if(n <= 3) {
return n;
}
//int max = 1000001;
int max = (n+1);
int nums[] = new int[max];
// Initialize array
for (int i = 0; i < max; ++i) {
nums[i] = -1;
}
nums[0] = 0;
nums[1] = 1;
nums[2] = 2;
nums[3] = 3;
// Precompute
for (int i = 0; i < max; ++i) {
if (nums[i] == -1 || (((i - 1) >= 0) && (nums[i] > (nums[i - 1] + 1)))) {
nums[i] = nums[i - 1] + 1;
}
for (int j = 1; (j <= i && j * i < max); ++j)
if (nums[j * i] == -1 || (nums[i] + 1) < nums[j * i])
nums[j * i] = nums[i] + 1;
}
System.out.println("n is " + n + ", answer is " + nums[n]);
return nums[n];
}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Down to Zero II
You are viewing a single comment's thread. Return to all comments →
Hi! Thanks a lot for the great idea! I tried to implement based on your idea!
I tried to reimplement with Java, but still got timeout error :( I guess problem is because I am looping several times through nums array ? (e.g. Initialize array part..)
It would be really helpful if someone help me out! Thanks a lot for help in advance :)