Commonly asked Data Structures and Algorithms Problems by big tech and different solution approaches with code in Java and C

Powered by Blogger.

Friday, June 30, 2017

Gaming Array Hackerrank solution in java


Explanation:

Function getmaxloc will give location of max element(pos) and from that we will check again with limit till pos until there is no element.

Code:

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {
    public static boolean  flag=false;
    public static int getmaxloc(int n,int arr[])
    {
        int max=arr[0];
        int pos=0;
        for(int i=1;i<n;i++)
        {
            if(max<arr[i])
               { max=arr[i];
               pos=i;
               }
        }
        return pos;
    }
    public static void check(int arr[],int n)
    {
        if(n==0)
            return;
        int pos=getmaxloc(n,arr);
        flag=!flag;
        check(arr,pos);
    }
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int t = in.nextInt();
        while(t-->0){
            flag=false;
            int g = in.nextInt();
            int arr[]=new int[g];
        for(int a0 = 0; a0 < g; a0++){
             arr[a0] = in.nextInt();
        }
            check(arr,g);
        if(!flag)
            System.out.println("ANDY");
        else
            System.out.println("BOB");
    }}
}


Another APproach :

Check for no. of times we encounter a max from 1 to n if it is divisible by 2 then player a wins else b wins.


for (int i = 0; i < n; i++) {
                int number = in.nextInt();
                if (max < number) {
                    max = number;
                    count++;
                }
            }
            System.out.println(count % 2 == 0 ? "ANDY" : "BOB");
        }



0 Comments:

Post a Comment

Stats