You are viewing a single comment's thread. Return to all comments →
My Solution in Java 8, O(n) time and O(1) space
public static long candies(int n, List<Integer> arr) { int streakUp = 1, streakDown = 1, lastStreakUp = 1; long total = 1; for(int i = 0; i<n-1; i++){ if(arr.get(i) > arr.get(i+1)){ streakDown++; if(lastStreakUp > streakDown-1){ total += streakDown-1; }else{ total += streakDown; } streakUp = 1; } else if(arr.get(i) < arr.get(i+1)){ streakUp++; streakDown = 1; total += streakUp; lastStreakUp = streakUp; } else{ streakUp = streakDown = lastStreakUp = 1; total++; } } return total; }
Seems like cookies are disabled on this browser, please enable them to open this website
Candies
You are viewing a single comment's thread. Return to all comments →
My Solution in Java 8, O(n) time and O(1) space