Leet Code Problem

I'm not sure why my solution to the question below is incorrect despite it being translated from Python. Can someone please help me out?

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 .

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.

func dominantIndex(_ nums: [Int]) -> Int {
    var maxmium = nums.max()
    
    for i in 0...nums.count {
        
        if nums[i] == maxmium{
            maxmium = i
        }
        if nums[i] != maxmium! && maxmium!<2*(nums[i]) {
            return -1
        }
    }
     return maxmium!
    
    // get max
    // divide max by every element
    // keep track of index
    // return max
}

You've swapped the maximum value for its index but then calculate whether it's less than twice the current value, which is often going to be true. You need to track the values separately.

Additionally, your solution iterates the values twice. You should try to do it once.

Terms of Service

Privacy Policy

Cookie Policy