Suppose we have an integer array called nums, now there is always exactly one largest element. We have to check whether the largest element in the array is at least twice as much as every other number in the array. If it is so, then we have to find the index of the largest element, otherwise return -1.
So, if the input is like [3,6,1,0], then the output will be 1, as 6 is the largest number, and for every other number in the array x, 6 is more than twice as big as x. As the index of 6 is 1, then the output is also 1.
To solve this, we will follow these steps −
Let us see the following implementation to get better understanding −
class Solution: def dominantIndex(self, nums): maximum = max(nums) for i in range(len(nums)): if nums[i] == maximum: maxindex = i if nums[i] != maximum and maximum < 2*(nums[i]): return -1 return maxindex ob = Solution() print(ob.dominantIndex([3, 6, 1, 0]))
[3, 6, 1, 0]