-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathCandies.java
More file actions
68 lines (53 loc) · 1.6 KB
/
Copy pathCandies.java
File metadata and controls
68 lines (53 loc) · 1.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// link: https://www.hackerrank.com/challenges/candies
// name: Candies
package hacker_rank;
import java.util.Scanner;
/**
*
* Alice is a kindergarden teacher. She wants to give some candies to the
* children in her class. All the children sit in a line, 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.
*
* Input The first 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.
*
* Ouput Output a single line containing the minimum number of candies Alice
* must buy.
*
* Constraints 1 <= N <= 10^5, 1 <= rating[i] <= 10^5
*
* @author mislav
*
*/
public class Candies {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] ratings = new int[n];
for (int i = 0; i < n; i++) {
ratings[i] = in.nextInt();
}
int[] left = new int[n];
int[] right = new int[n];
for (int i = 1; i < n; i++) {
if (ratings[i] > ratings[i - 1]) {
left[i] = left[i - 1] + 1;
}
}
for (int i = n - 2; i >= 0; i--) {
if (ratings[i] > ratings[i + 1]) {
right[i] = right[i + 1] + 1;
}
}
int solution = 0;
for (int i = 0; i < n; i++) {
solution += Math.max(left[i], right[i]) + 1;
}
System.out.print(solution);
in.close();
}
}