Largest Number At Least Twice of Others

Largest Number At Least Twice of Others in java

You are given an integer array nums where the largest integer is unique.

Determine whether the largest element in the array is at least twice as much as every other number in the array. If it is, print the index of the largest element, or print -1 otherwise.

Input:

The first line of the input contains the number 𝑛(length of array) The next n integers denotes the elements of the array.

Output:

print the index of the element if it satisfies the condition else print -1

Constraints:

1 <= nums.length <= 50
0 <= nums[i] <= 100
The largest element in nums is unique.
Sample Input 1

4 3 6 1 0

Sample Output 1

1

Explanation

6 is the largest integer. For every other number in the array x, 6 is at least twice as big as x. The index of value 6 is 1, so we return 1.

Sample Input 2
4
1 2 3 4
Sample Output 2
-1
Explanation

4 is less than twice the value of 3, so we return -1.

Solution Largest Number At Least Twice of Others :–

import java.util.*;
import java.lang.*;
import java.io.*;

public class Main
{
	public static void main (String[] args) throws java.lang.Exception
	{
		//your code here
      Scanner sc = new Scanner(System.in);
      int n = sc.nextInt();
      int arr[] = new int[n];

      for(int i=0;i<n;i++)
        {
          arr[i]=sc.nextInt();
        }

      int temp=0,max=arr[0];
        for(int i=1;i<n;i++)
          { 
            if(max<arr[i])
                 {
                   temp=i;
                   max=arr[i];
                 }
          }

      int demo=0;
      for(int j=0;j<n;j++)
        {
          if(temp!=j && arr[temp] < (arr[j]*2))
          {
            demo++;
          }
        }
      
      if(demo>0)
      {
        System.out.println("-1");
      }
      else{
        System.out.println(temp);
      } 
   }
}

Add a Comment

Your email address will not be published. Required fields are marked *