Wednesday, November 19, 2014

Hacker Rank - Priyanka and Toys

Little Priyanka visited a kids' shop. There are N toys and their weight is represented by an array W=[w1,w2,,wN]. Each toy costs 1 unit, and if she buys a toy with weight w, then she can get all other toys whose weight lies between [w,w+4] (both inclusive) free of cost.
Input Format
The first line contains an integer N i.e. number of toys.
Next line will contain N integers, w1,w2,,wN, representing the weight array.
Output Format
Minimum units with which Priyanka could buy all of toys.
Solution C#
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Solution {
    static void Main(String[] args) {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution */
         Int32 N = Convert.ToInt32(Console.ReadLine());//5;
            Int32[] w = Console.ReadLine().ToString().Split(' ').Select(n => Convert.ToInt32(n)).ToArray(); ; //{ 1, 2, 3, 17, 10 };

            Array.Sort(w);
            Int32 unit = 0; Int32 W = 0;
            for (int i = 0; i < w.Length; i++)
            {
                if (i == 0) { unit++; W = w[i]+4; }
                else
                {
                    if (w[i] > W) { unit++; W = w[i] + 4; }
                }

            }
            Console.WriteLine(unit);
    }
}

Hacker Rank -Chief hopper

Chief's bot is playing an old DOS-based game. There are N+1 buildings in the game - indexed from 0 to N and are placed left-to-right. It is guaranteed that building with index 0 will be of height 0 unit. For buildings with index i (i[1,N]) height will be hi units.

At beginning Chief's bot is at building with index 0. At each step, bot jumps to next (right) building. Suppose bot is at kth building and his current energy is botEnergy, then in next step he will jump to (k+1)th building. He will gain/lose energy equal in amount to difference between hk+1 and botEnergy
  • If hk+1>botEnergy, then he will lose hk+1botEnergy units of energy.
  • Otherwise, he will gain botEnergyhk+1 units of energy.
Goal is to reach Nth building, and during the course bot should never have negative energy units. What should be the minimum units of energy with which bot should start to successfully complete the game?
Input Format
The first line contains integer N. Next line contains N space separated integers h1,h2,,hN representing the heights of the buildings.
Output Format
Print a single number representing minimum units of energy required to complete the game.
Solution [Python]



N = int(input())
h = [int(x) for x in input().split(" ")]
i=0
Energy=0

r=len(h)
while 1:
    botEnergy=Energy
    for x in range(0,len(h)):
        if(h[x]>botEnergy):
            botEnergy=botEnergy-(h[x]-botEnergy)
        else:
            botEnergy=botEnergy+(botEnergy-h[x])

        if(botEnergy<0):
            break
    if(botEnergy>0):
        print(Energy)
        break
    else:
        Energy=Energy+1