Sunny and Johnny like to pool their money and go to the ice cream parlor. Johnny never buys the same flavor that Sunny does. The only other rule they have is that they spend all of their money.
Given a list of prices for the flavors of ice cream, select the two that will cost all of the money they have.
For example, they have  to spend and there are flavors costing . The two flavors costing  and  meet the criteria. Using -based indexing, they are at indices  and .


Question from hackerrank.


Solution in C# - 

class Solution {

    static int[] icecreamParlor(int m, int[] arr) {

        int[] dup = new int[arr.Length];
        Array.Copy(arr,dup,arr.Length);
        int[] result = new int[2];
        Array.Sort(arr);
        int l = 0;
        int r = arr.Length-1;
        int x = 0, y = 0;
        while(l<r)
        {
            if(arr[l]+arr[r] == m)
            {
                x = arr[l];
                y = arr[r];
                break;
            }
            else if(arr[l] + arr[r] < m)
            l++;
            else
            r--;
        }

        result[0] = Array.IndexOf(dup,x)+1;
        result[1] = Array.LastIndexOf(dup,y)+1;
        Array.Sort(result);
        return result;

    }

    static void Main(string[] args) {
        TextWriter textWriter = new StreamWriter(@System.Environment.GetEnvironmentVariable("OUTPUT_PATH"), true);

        int t = Convert.ToInt32(Console.ReadLine());

        for (int tItr = 0; tItr < t; tItr++) {
            int m = Convert.ToInt32(Console.ReadLine());

            int n = Convert.ToInt32(Console.ReadLine());

            int[] arr = Array.ConvertAll(Console.ReadLine().Split(' '), arrTemp => Convert.ToInt32(arrTemp));
           
            int[] result = icecreamParlor(m, arr);

            textWriter.WriteLine(string.Join(" ", result));
        }

        textWriter.Flush();
        textWriter.Close();
    }

}



Post a Comment

Previous Post Next Post