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.






Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

Top comments (0)

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay