DEV Community

Ronaldo Peres
Ronaldo Peres

Posted on • Edited on

3

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.






AWS Q Developer image

Your AI Code Assistant

Generate and update README files, create data-flow diagrams, and keep your project fully documented. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay