
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Largest Number At Least Twice of Others in Python
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 −
- maximum := maximum of nums
- for i in range 0 to size of nums, do
- if nums[i] is same as maximum, then
- maxindex := i
- if nums[i] is not same as maximum and maximum < 2*(nums[i]), then
- return -1
- if nums[i] is same as maximum, then
Let us see the following implementation to get better understanding −
Example
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]))
Input
[3, 6, 1, 0]
Output
1
- Related Articles
- Program to find largest average of sublist whose size at least k in Python
- Largest sum subarray with at-least k numbers in C++
- Largest Number in Python
- Get at least x number of rows in MySQL?
- Largest Unique Number in Python
- Python Program to Extract Strings with at least given number of characters from other list
- Largest Number By Two Times in Python
- How to check if a string has at least one letter and one number in Python?
- Program to find number of elements in A are strictly less than at least k elements in B in Python
- Insert 5 to Make Number Largest in Python
- A die is thrown twice. What is the probability that 5 will come up at least once?
- Python - Largest number possible from list of given numbers
- Python program to find largest number in a list
- Python Program for Find largest prime factor of a number
- Program to find size of smallest sublist whose sum at least target in Python

Advertisements