Tuesday, June 9, 2015

Google : Number of Boats for 2Kids Maximum 150 bls

private static int GetMaxBoats(List<int> arr)
        {
            arr.Sort();
            /*foreach (int n in arr)
            {
                Console.WriteLine(n);
            }*/

            int lowIndex = 0;
            int highIndex = arr.Count - 1;
            int boatCounter = 0;

            while(lowIndex < highIndex)
            {
                if(arr[lowIndex] + arr[highIndex] <= 150)
                {
                    //2 kids fit
                    boatCounter++;
                    lowIndex++;
                    highIndex--;
                }
                else
                {
                    
                    if(arr[highIndex] <= 150)
                    {
                        // only 1 kid fits, put the larger kid in the boat if he fits
                        boatCounter++;
                    }
                    // Else, larger kid is too heavy to go on boat.

                    // Either way, we've handled the heavier child
                    highIndex--;
                }

                // cover case where both pointers point to same child
                if(lowIndex == highIndex)
                {
                    if (arr[highIndex] <= 150)
                    {
                        boatCounter++;
                    }

                    break;
                }
            }

            return boatCounter;
        }

No comments:

Post a Comment