Skip to content

Instantly share code, notes, and snippets.

@Earu
Last active October 10, 2024 13:11
Show Gist options
  • Save Earu/e8cb35bbf9c055c4f6588af06a984a3a to your computer and use it in GitHub Desktop.
Save Earu/e8cb35bbf9c055c4f6588af06a984a3a to your computer and use it in GitHub Desktop.
Code for the "Jesse and cookies" challenge on hackerrank.com
/*
Jesse loves cookies and wants the sweetness of some cookies to be greater than value K.
To do this, two cookies with the least sweetness are repeatedly mixed. This creates a special combined cookie with:
(least sweet cookie) + (2 * (second least sweet cookie))
This occurs until all the cookies have a sweetness >= K.
Given the sweetness of a number of cookies, determine the minimum number of operations required. If it is not possible, return -1.
*/
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.Text.RegularExpressions;
using System.Text;
using System;
class Result
{
/*
* Complete the 'cookies' function below.
*
* The function is expected to return an INTEGER.
* The function accepts following parameters:
* 1. INTEGER k
* 2. INTEGER_ARRAY A
*/
public static int cookies(int k, List<int> A)
{
if (A.Count == 0) return -1;
int startIndex = 0;
int iters = 0;
while (A.Count > 0) {
A.Sort();
if (A[startIndex] >= k) return iters;
if ((A.Count - startIndex) == 1 && A[startIndex] < k) return -1;
int newCookie = (2 * A[startIndex + 1]) + A[startIndex];
startIndex += 2;
A.Add(newCookie);
iters++;
}
return -1;
}
}
class Solution
{
public static void Main(string[] args)
{
TextWriter textWriter = new StreamWriter(@System.Environment.GetEnvironmentVariable("OUTPUT_PATH"), true);
string[] firstMultipleInput = Console.ReadLine().TrimEnd().Split(' ');
int n = Convert.ToInt32(firstMultipleInput[0]);
int k = Convert.ToInt32(firstMultipleInput[1]);
List<int> A = Console.ReadLine().TrimEnd().Split(' ').ToList().Select(ATemp => Convert.ToInt32(ATemp)).ToList();
int result = Result.cookies(k, A);
textWriter.WriteLine(result);
textWriter.Flush();
textWriter.Close();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment