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 max = 0;
    int secondMax = 0;

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

    return max >= 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 max = 0;
    int secondMax = 0;

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

    return max >= 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:
    max = 0
    secondMax = 0

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

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