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

The Future of AI, LLMs, and Observability on Google Cloud

Datadog sat down with Google’s Director of AI to discuss the current and future states of AI, ML, and LLMs on Google Cloud. Discover 7 key insights for technical leaders, covering everything from upskilling teams to observability best practices

Learn More

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

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay