Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created December 25, 2017 20:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jianminchen/717f57301f4860ad65f3cf380503a72a to your computer and use it in GitHub Desktop.
Save jianminchen/717f57301f4860ad65f3cf380503a72a to your computer and use it in GitHub Desktop.
Array related linear scan - 22 minutes practice - with a few bugs in the first writing and caught up while doing whiteboard testing.
using System;
class Solution
{
public static double FindGrantsCap(double[] grantsArray, double newBudget) // 2, 100, 50, 120, 1000
{
if(grantsArray == null || grantsArray.Length == 0 || newBudget <=0 ) // false
{
return 0;
}
Array.Sort(grantsArray); // 2, 50, 100, 120, 1000
int length = grantsArray.Length; // 5
double sum = 0; // 0
for(int i = 0; i < length; i ++) //
{
var visit = grantsArray[i]; // 2, 50
var restItems = length - i;
// do a test
var hasEnoughMoney = (sum + visit * restItems) < newBudget; // 0 + 2 * 5 < 190, 2 + 50 * 4 < 190
if(!hasEnoughMoney) // true
{
return (newBudget - sum)/ restItems; // (190 - 2)/ 4 = 47
}
sum += visit; // sum = 2
}
// edge case
return grantsArray[length - 1];
}
static void Main(string[] args)
{
var grantsArray = new double[]{2, 100, 50, 120, 1000};
Console.WriteLine(FindGrantsCap(grantsArray, 190));
}
}
// input: grantsArray = [2, 100, 50, 120, 1000], newBudget = 190
// output: 47
// cap
// 2, 50 , 100, 120, 1000 ->
// 47
// 2, -> 5 * 2 = 10 -> 190
// 50 - 2 + 50 * 4 = 202 > 190 -> less than
// (190 - 2)/ 4 = 188/4 = 47
// test - new budget -> cap , 2 - 50
// https://leetcode.com/articles/can-place-flowers/
// https://www.hackerrank.com/challenges/bear-and-steady-gene/problem
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment