Help them Out

Three friends Bob , Alice and Peter are giving a coding contest where they are given a array problem which they are expected to solve in order to win the contest . Help them to win the contest .The problem is given below.

They are suppose to find the number of steps(moves) required to convert the given array to zero array(an array in which every element is 0)

Condition : 

Only 2 moves are possible (  Decrement and half operations ):

1) The decrement operator decreses the value of an element in the array by 1 .

2) Half operation halfs the value of each element in the array.

Example:

Input:  n=5,a[] = { 10, 11, 12, 11, 10 };
Output: 15

Approach

Java


public class HelpThemOut {
    public static void main(String args[]) {
        int n = 5;
        int a[] = { 1011121110 };
        int moves = 0, stars = 0;
        for (int i = 0; i < n; i++) {
            int x = a[i];
            int s = 0;
            while (x > 0) {
                if (x % 2 == 1) {
                    moves++;
                    x -= 1;
                } else {
                    x /= 2;
                    s++;
                }
            }
            stars = Math.max(stars, s);
        }
        System.out.println(moves + stars);
    }
}


No comments:

Post a Comment