Largest Number At Least Twice of Others

Easy
10
61.5% Acceptance

In this lab, you are supposed to implement a function called dominantIndex that takes an integer array nums as input, where the largest integer is unique. Your task is to determine whether the largest element in the array is at least twice as much as every other number in the array. If it is, return the index of the largest element, or return -1 otherwise.

Please follow the given rules carefully and make sure to export the necessary functions, variables, or any other items necessary for the evaluation script.

Function Signature

/** * @param {number[]} nums * @return {number} */ const dominantIndex = (nums) => { // Your implementation goes here };

Example

Example 1

Input: nums = [3, 6, 1, 0]

Output: 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.

Example 2

Input: nums = [1, 2, 3, 4]

Output: -1

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

Example 3

Input: nums = [0, 0, 3, 1]

Output: 2

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

Constraints:

  • 2 <= nums.length <= 50
  • 0 <= nums[i] <= 100
  • The largest element in nums is unique.