Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
C Candies
By Mohammad Noor Abu Khleif / In Problems Solving / February 24, 2017 / Add comment
Privacy - Terms
p
P
Alice is a kindergarten teacher. She wants to give some candies to the children in her class.
All the children sit in a line ( their positions are xed), and each of them has a rating score
according to his or her performance in the class. Alice wants to give at least 1 candy to each
child. If two children sit next to each other, then the one with the higher rating must get more
candies. Alice wants to save money, so she needs to minimize the total number of candies
given to the children.
Input Format
The rst line of the input is an integer N, the number of children in Alice’s class. Each of the
following N lines contains an integer that indicates the rating of each child.
Output Format
Output a single line containing the minimum number of candies Alice must buy.
Sample Input
3 1 2 2
Sample Output
Explanation
Here 1, 2, 2 is the rating. Note that when two children have equal rating, they are allowed to
have di erent number of candies. Hence optimal distribution will be 1, 2, 1.
My Solution (Java):
1. import java.util.Scanner;
2.
3. public class Solution {
4. static Scanner sc;
5.
6. public static void main(String[] args) {
7. int N; // number of students
8. long C = 0; // Number of Candies
9. int[] ratings;
10. int[] candies;
11. int prvs, crnt; // previous, and current rating
12. sc = new Scanner(System.in);
13. N = sc.nextInt();
14.
15. ratings = new int[N];
16. candies = new int[N];
17.
18. // read ratings:
19. for (int i = 0; i < N; i++) {
20. ratings[i] = sc.nextInt();
21. }
22.
23. prvs = crnt = ratings[0];
24. candies[0] = 1;
25. for (int i = 1; i < N; i++) {
26. crnt = ratings[i];
27. if (crnt > prvs) {
28. candies[i] = candies[i - 1] + 1;
29. } else {
30. candies[i] = 1;
31. }
32. prvs = crnt;
33. }
34.
35. // Revisit and count candies
36. prvs = crnt = ratings[N - 1];
37. C = candies[N - 1];
38. for (int i = N - 2; i >= 0; i--) {
39. crnt = ratings[i];
40. if (crnt > prvs && candies[i + 1] >= candies[i]) {
41. candies[i] = candies[i + 1] + 1;
42. }
43. C += candies[i];
44. prvs = crnt;
45. }
46. System.out.println(C);
47. }
48. }
https://www.hackerrank.com/challenges/candies
Abu Khleif arrays Java Java Exercises loops nested loops OOP
questions
ADD COMMENT
Comment
Submit Comment
This site uses Akismet to reduce spam. Learn how your comment data is processed.
READ MORE
F M
Fall Semester 2014 –
Multiply and Divide
Second Exam Lecture 1 :
Function | C++
Loops
In C++ Exercises / August 20, 2017 /
In C++ Lectures / November 19, 2014 /
1 Min read
1 Min read
J L
Java Exercise #02 – Sort 3
Largest of 3 Numbers
Numbers
In Java Exercises / October 17, 2015 /
In Java Exercises / September 16, 2014 /
1 Min read
1 Min read
/* ]]> */