Hackerrank jumping on the clouds revisited solution

Farzin Pashaee
3 min readMar 11, 2022

--

In this article, you can find the solution for the Hackerrank jumping on the clouds revisited challenge. Here is the description of the challenge according to Hackerrank:

A child is playing a cloud hopping game. In this game, there are sequentially numbered clouds that can be thunderheads or cumulus clouds. The character must jump from cloud to cloud until it reaches the start again.

There is an array of clouds and an energy level . The character starts from and uses unit of energy to make a jump of size to cloud . If it lands on a thundercloud, , its energy () decreases by additional units. The game ends when the character lands back on cloud .

Given the values of , and the configuration of the clouds as an array , determine the final value of after the game ends.

As you can see from the description, the input of the expected method will be an array of 1,0 and also an integer which is the size of the jump. Using an example can make it much easier to understand. let's consider we have the following input and find the expected result accordingly.

int[] clouds = {0, 0, 1, 0, 0, 1, 1, 0];
int k = 2;

Now if we want to visualize this, it will look like something like this

Starting from cloud 0 we will jump with size 2 until we get back to cloud 0. Considering that the initial energy level is 100 after each jump we will decrease 1 level and if we land in a thunderheads cloud we are going to lose an extra 2 points.

100 -> 97 -> 96 -> 93 -> 92
// the result will be 92

Solution

Now the following code will help to traverse the array and return the proper result based on the given jump size

static int jumpingOnClouds(int[] c, int k) {
int energyLevel = 100;
for( int i = k ; i != 0 ; i+=k ){
if( i >= c.length ) i = i - c.length;
energyLevel = energyLevel - 1;
if( c[i] == 1 ) energyLevel = energyLevel - 2;
if( i == 0 ) break;
}
return energyLevel;
}

As you can see we have a for loop which helps us move on clouds array using the k as the jump size. every step we will decrease 1 from the energy level and we will also check each item for cloud type in case the item of the array had a value of 1 we will decrease an additional 2 energy levels.

We do recommend that before just using the code try to solve the issue yourself and try this checking this solution in case you have failed to pass all the tests.

Hope this article helped you and please support me by your applaud for the story. if you don't know how it is just like this:

Or buy me a coffee here!

--

--

Farzin Pashaee

Software Engineer at Maybank, AI and ML enthusiastic