[LeetCode] Largest Number At Least Twice of Others

747. Largest Number At Least Twice of Others

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
int dominantIndex(vector<int>& nums) {
int ma = -1, res = -1;

for(int i = 0; i < nums.size(); i++) {
if(ma * 2 <= nums[i]) {
ma = nums[i];
res = i;
} else if(ma < nums[i] * 2) {
ma = max(ma, nums[i]);
res = -1;
}
}


return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/30/PS/LeetCode/largest-number-at-least-twice-of-others/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.