In this HackerRank Candies Interview preparation kit problem you need to complete the candies function.


HackerRank Candies interview preparation kit solution


Problem solution in Python programming.

N = int(input())
a = []
while N>0:
	a.append(int(input()))
	N -= 1
N = len(a)
left, right, num = [[0 for i in range(N)] for j in range(3)]
p = 1
while p<N:
	if a[p] > a[p-1]:
		left[p] = left[p-1] + 1
	p += 1
p = N-2
while p>=0:
	if a[p] > a[p+1]:
		right[p] = right[p+1] + 1
	p -= 1
p = 0
while p<N:
	num[p] = 1 + max(left[p], right[p])
	p += 1

print(sum(num))


Problem solution in Java Programming.

import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;

public class Solution {

    // Complete the candies function below.
    static long candies(int n, int[] arr) {

  int[] candies = new int[n];
  candies[0] = 1;
  for (int i = 1; i < n; i++) {
    if (arr[i] > arr[i - 1]) {
      candies[i] = candies[i - 1] + 1;
    } else {
      candies[i] = 1;
    }
  }

  for (int i = n - 2; i >= 0; i--) {
    if (arr[i] > arr[i + 1] && candies[i] <= candies[i + 1]) {
      candies[i] = candies[i + 1] + 1;
    }
  }

  long sum = 0;
  for (int c : candies) {
    sum += c;
  }
  return sum;
}

    private static final Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) throws IOException {
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));

        int n = scanner.nextInt();
        scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

        int[] arr = new int[n];

        for (int i = 0; i < n; i++) {
            int arrItem = scanner.nextInt();
            scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
            arr[i] = arrItem;
        }

        long result = candies(n, arr);

        bufferedWriter.write(String.valueOf(result));
        bufferedWriter.newLine();

        bufferedWriter.close();

        scanner.close();
    }
}


Problem solution in C++ programming.

#include <iostream>
#include <vector>
using namespace std;
int nums[100001]; // ratings
int allocated[100001]; // candies given. defaults to 0 (not processed)
vector<int> pos_by_rating[100001];
int main()
{
	int N;
	cin >> N;
	
	for (int x = 0; x < N; x++)
	{
		cin >> nums[x];
		allocated[x] = 0;
		pos_by_rating[nums[x]].push_back(x);
	}

	for (int rating = 1; rating <= 100000; rating++)
	{
		for (int q = 0; q < pos_by_rating[rating].size(); q++)
		{
			int pos = pos_by_rating[rating][q];
			int m = 0;
			if (pos > 0 && nums[pos-1] < nums[pos])
			{
				m = max(m, allocated[pos-1]);
			}

			if (pos < N-1 && nums[pos+1] < nums[pos])
			{
				m = max(m, allocated[pos+1]);
			}

			allocated[pos] = m+1;
		}
	}
		
	int sum = 0;
	for (int x = 0; x < N; x++)
	{
		//cout << allocated[x] << endl;
		sum += allocated[x];
	}
	cout << sum << endl;

	return 0;
}


Problem solution in C programming.

#include <stdio.h>
#include <stdlib.h>

#define MAXN 100000

struct stu{
    int id;
    int rating;
};

int comp( const void*p1, const void*p2){
    return ((struct stu*)p1)->rating - ((struct stu*)p2)->rating;
}

struct stu student[MAXN];
int candies[MAXN];
int ratings[MAXN];

int main(int argc, char *argv[])
{
    int N;
    int i,j;
    int candy;
    int id;
    long long sumcandies = 0;

    scanf("%d",&N);
    for(i = 0; i < N; i++){
        scanf("%d",&student[i].rating);
        student[i].id = i;
        ratings[i] = student[i].rating;
    }

    qsort(student,N,sizeof(struct stu),comp);
    
    for(i = 0; i < N; i++){
        id = student[i].id;
        candy = 1;

        if(id > 0){
            if(candies[id-1] != 0 && ratings[id] > ratings[id-1]){
                candy = candies[id-1] + 1;
            }
        }

        if(id < N-1){
            if(candies[id+1] != 0 && ratings[id] > ratings[id+1] &&
               candy <= candies[id+1]){
                candy = candies[id+1] + 1;
            }
        }

        sumcandies += candy;
        candies[id] = candy;
    }

    printf("%lld\n",sumcandies);
    return 0;
}


Problem solution in JavaScript programming.

function processData(input) {
    //Enter your code here
    var arr = input.split('\n');
    var sum = 1, tempRank = 1, peakPos = 1, peakVal = 1;
    for (var i = 2; i < arr.length; i++) {
        if (parseInt(arr[i]) > parseInt(arr[i-1])) {
            tempRank++;
            sum += tempRank;
            peakPos = i;
            peakVal = tempRank;
 //          console.log("bigger: " + sum);
        } else if (parseInt(arr[i]) < parseInt(arr[i-1])) {
            if (tempRank > 1) {
                peakVal--;
                sum++;
            } else {
                sum += (i - peakPos);
                peakVal--;
                if (peakVal == 0) {
                    peakVal = 1;
                    sum++;
                }
            }
            tempRank = 1;
//           console.log("smaller: " + sum);
        } else {
           /* if (tempRank > 1) {
                peakVal--;
                if (peakVal == 0) {
                    peakVal = 1;
                    sum++;
                }
            }*/
            
            peakVal = 1;
            peakPos = i;
            tempRank = 1;
            sum++;
 //             console.log("equal: " + sum);
        }
    }
    
    console.log(sum);
} 

process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
    _input += input;
});

process.stdin.on("end", function () {
   processData(_input);
});