I am studying algorithms and I solved this problem under Dynamic Programming section:
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 fixed), 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 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.
Code:
import java.io.*;
import java.util.*;
public class Candie{
static int candieCalculator(int[] numbers) {
int len = numbers.length;
int result=0;
if (len==1) {
return 1;
}
for (int i=0; i<len; i++) {
result++;
if (i==0) {
if (numbers[i] > numbers[i+1]) {
result++;
}
}
else if (i==len-1) {
if (numbers[i] > numbers[i-1]) {
result++;
}
}
else {
if (numbers[i] > numbers[i+1]) {
result++;
}
if (numbers[i] > numbers[i-1]) {
result++;
}
}
}
return result;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] numbers = new int[n];
for(int i=0; i < n; i++) {
numbers[i] = in.nextInt();
}
System.out.println(candieCalculator(numbers));
}
}
Sample input:
3 1 2 2
Sample output:
4
What do you think? Also this solution is considered as DP? It doesn't look DP to me.