#747
Easy Algorithms Largest number at least twice of others
Array Sorting
52.1% acceptance
Feb 21, 2026
1370
953
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, return the index of the largest element, or return -1 otherwise.
Solution
Rust
Time O(n)
Space O(1)
/*
* 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, return the index of the largest element, or return -1 otherwise.
* 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.
* Constraints:
* 2 <= nums.length <= 50
* 0 <= nums[i] <= 100
* The largest element in nums is unique.
*/
impl Solution {
pub fn dominant_index(nums: Vec<i32>) -> i32 {
let max_val = *nums.iter().max().unwrap();
let max_idx = nums.iter().position(|&x| x == max_val).unwrap();
if nums.iter().all(|&x| max_val >= 2 * x || x == max_val) {
max_idx as i32
} else {
-1
}
}
}