Skip to content

747. Largest Number At Least Twice of Others

  • Time: $O(n)$
  • Space: $O(1)$
 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 ans;
    int mx = 0;
    int secondMax = 0;

    for (int i = 0; i < nums.size(); ++i)
      if (nums[i] > mx) {
        secondMax = mx;
        mx = nums[i];
        ans = i;
      } else if (nums[i] > secondMax) {
        secondMax = nums[i];
      }

    return mx >= 2 * secondMax ? ans : -1;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
  public int dominantIndex(int[] nums) {
    int ans = 0;
    int mx = 0;
    int secondMax = 0;

    for (int i = 0; i < nums.length; ++i)
      if (nums[i] > mx) {
        secondMax = mx;
        mx = nums[i];
        ans = i;
      } else if (nums[i] > secondMax) {
        secondMax = nums[i];
      }

    return mx >= 2 * secondMax ? ans : -1;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution:
  def dominantIndex(self, nums: list[int]) -> int:
    mx = 0
    secondMax = 0

    for i, num in enumerate(nums):
      if num > mx:
        secondMax = mx
        mx = num
        ans = i
      elif num > secondMax:
        secondMax = num

    return ans if mx >= 2 * secondMax else -1