0

I am trying to improve my linq syntax coding and i was wondering if anyone could show me a better way of writing this code below.Question is taken from leetcode https://leetcode.com/problems/kids-with-the-greatest-number-of-candies/. Thanks

        public static IList<bool> KidsWithCandies(int[] candles, int extraCandies)
        {
           var kidCandle = candles.Select(x => x+ extraCandies);
           var con = new List<bool>();
            foreach(var kid in kidCandle)
            {
                if (kid >= candles.Max())
                    con.Add(true);
                else
                    con.Add(false);
            }

           return con;
        }

https://leetcode.com/problems/kids-with-the-greatest-number-of-candies/

1
  • int max = candles.Max(); List<bool> con = candles.Select(x => x + extraCandies>= max).ToList(); Commented May 29, 2020 at 16:30

1 Answer 1

3

Linq also does looping but just a syntacitc sugar, but we can write a Select for the foreach. So the code :

var con = new List<bool>();
foreach(var kid in kidCandle)
{
    if (kid >= candles.Max())
        con.Add(true);
    else
        con.Add(false);
}

can be replaced with:

public static IList<bool> KidsWithCandies(int[] candles, int extraCandies)
{
   var kidCandle = candles.Select(x => x+ extraCandies);
   var maxCandles = candles.Max();
   var con = kidCandle.Select(kid => (kid >= maxCandles)).ToList();
   return con;
}

even the whole method could be written like:

public static IList<bool> KidsWithCandies(int[] candles, int extraCandies)
{
    var maxCandles = candles.Max();
    return candles.Select(x => x+ extraCandies)
                 .Select(kid => (kid >= maxCandles)).ToList();
}

Now more simpler:

public static IList<bool> KidsWithCandies(int[] candles, int extraCandies)
{
   var maxCandles = candles.Max();
   var con = candles.Select(kid => (kid + extraCandies >= maxCandles)).ToList();
   return con;
}

we can even avoid var :

 public static IList<bool> KidsWithCandies(int[] candles, int extraCandies)
 {
     var maxCandles = candles.Max();     
     return candles.Select(kid => (kid + extraCandies >= maxCandles)).ToList();
 }
Sign up to request clarification or add additional context in comments.

3 Comments

You don't need to ? true : false something that's already a boolean. It's kind of like doing bool foo = true ? true : false;
Or public static IList<bool> KidsWithCandies(int[] candles, int extraCandies) => candles.Select(kid => (kid + extraCandies >= candles.Max()));
Current query has complexity O(n^2), due to calculating Max in every Select call. It is strongly advised to move Max calculation to dedicated variable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.