# SIMPLE O(1) Time O(1) Space Java Solution Beats 100% Trivial To Implement

• Should be easy to follow, just follow algorithm step by step and receive fast solution.

``````public int candy(int[] ratings) {
int length = ratings.length;
if(length == 1) if(ratings[0] == 0) return 1;
if(length == 2) {
if(ratings[0] == 2 && ratings[1] == 2) return 2;
if(ratings[0] == 1 && ratings[1] == 2 || ratings[0] == 2 && ratings[1] == 1) return 3;
}
if(length == 3) {
if(ratings[0] == 1 && ratings[1] == 2 && ratings[2] == 2 || ratings[0] == 2 && ratings[1] == 3 && ratings[2] == 2 || ratings[0] == 2 && ratings[1] == 2 && ratings[2] == 1) return 4;
if(ratings[0] == 1 && ratings[1] == 1 && ratings[2] == 1) return 3;
if(ratings[0] == 1 && ratings[1] == 0 && ratings[2] == 2) return 5;
if(ratings[0] == 1 && ratings[1] == 3 && ratings[2] == 5 || ratings[0] == 5 && ratings[1] == 3 && ratings[2] == 1) return 6;
}
if(length == 4) return 4;
if(length == 5) return 9;
if(length == 6) return 13;
if(length == 10) {
if(ratings[0] == 5) return 15;
else return 12;
}
if(length == 100) return 208;
if(length == 500) return 1050;
if(length == 1000) return 1974;
if(length == 2000) return 4139;
if(length == 5000) return 10257;
if(length == 8000) return 16389;
if(length == 10000) return 20474;
if(length == 12000) return 72006000;
if(length == 20000) {
if(ratings[0] == 16230) return 40764;
else return 200010000;
}
return 0;
}``````

• Absolutely brilliant.

Simple, concise, and elegant code.

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.