DEV Community

Ronaldo Peres
Ronaldo Peres

Posted on • Updated on

Days of code [2]

The challenge today was this one:

"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."

So, to solve this one:

Step by step

  • Get largest int in the array, lets call this var as 'max'
  • Get index of largest int in the array
  • After that, sort the array
  • And reverse it
  • With this I created a new array without the first item, cause it was the largest int
  • Multiply all int by 2 in the new array
  • Now get the largest number in this new array, lets call this var as newMax
  • Now check if Max is equal or higher than newMax, if so return tne index that was taken before, if not set result to -1

So, we have:

    public static class LargestNumberInArray
    {
        public static int DominantIndex(int[] nums)
        {
            int result = -1;

            if (nums.Length == 1) return 0;

            // Get largest number and respective index
            int max = nums.Max();
            int tempResult = Array.IndexOf(nums, max);

            Array.Sort(nums);

            // Sort array in desc order and get a new one skipping first number as we know it is the largest
            var arr = nums.Reverse().Select(x => x * 2).ToArray().Skip(1);

            int newMax = arr.Max();

            if (max >= newMax)
            {
                result = tempResult;
            }

            return result;
        }
    }

Enter fullscreen mode Exit fullscreen mode

Challenges

Objective: solve different challenges from different sites such as Code wars, Hacker rank.

Top comments (0)