LeetCode Solutions

747. Largest Number At Least Twice of Others

Time: $O(n)$

Space: $O(1)$

			

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;
  }
};
			

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;
  }
}
			

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