Challenges
Objective: solve different challenges from different sites such as Code wars, Hacker rank.
Posted on September 8, 2021
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:
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;
}
}
Objective: solve different challenges from different sites such as Code wars, Hacker rank.
Posted on September 8, 2021
Sign up to receive the latest update from our blog.
September 19, 2024
April 7, 2024