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 a 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 a cloud.
Given the values of ,, and the configuration of the clouds as an array, determine the final value after the game ends.
Example:
Input: n=8,k=2,arr[]={0,0,1,0,0,1,1,0}
Output: 92
Approach
Java
public class JumpingClouds {public static void main(String[] args) {int k = 2;int[] arr = { 0, 0, 1, 0, 0, 1, 1, 0 };System.out.println(jumpingOnClouds(arr, k));}static int jumpingOnClouds(int[] arr, int k) {int i = 0, e = 100;int n = arr.length;while (true) {i = (i + k) % n;if (arr[i] == 1) {e = e - 1 - 2;} else {e = e - 1;}if (i == 0) {break;}}return e;}}
C++
#include <bits/stdc++.h>using namespace std;int jumpingOnClouds(vector<int> arr, int k){int i = 0, e = 100;int n = arr.size();while (true){i = (i + k) % n;if (arr[i] == 1){e = e - 1 - 2;}else{e = e - 1;}if (i == 0){break;}}return e;}int main(){int n = 8, k = 2;vector<int> arr = {0, 0, 1, 0, 0, 1, 1, 0};cout << jumpingOnClouds(arr, k);return 0;}
No comments:
Post a Comment