Leetcode 748 Solution

This article provides solution to leetcode question 748 (largest-number-at-least-twice-of-others)

https://leetcode.com/problems/largest-number-at-least-twice-of-others

Solution

class Solution {
public:
    int dominantIndex(vector<int>& nums) {
        int second_largest = -1;
        int largest = -1;
        int index = -1;

        for (int i = 0; i < nums.size(); i++)
        {
            int num = nums[i];

            if (num > largest)
            {
                second_largest = largest;
                largest = num;
                index = i;
            }
            else if (num > second_largest)
                second_largest = num;
        }

        return largest >= second_largest * 2 ? index : -1;
    }
};