• + 0 comments

    My solution is based on observation that each student should get at least d candies, where d is the length of the longest decreasing subsequence in arr starting from this student. E.g. if scores are 8 6 3, then first student should get at least 3 candies, second should get at least 2, etc.

    On the other hand, each student should get at least one more candy then their left colleague if they have a higher score. That is why we have the formula:

    candies[i] = max(longest_decreasing_subsequence[i], candies[i - 1] + 1)

    public  static  long candies(int n, List<Integer> arr) {
    
    int[] decreasing = new  int[n];
    decreasing[n - 1] = 1;
    for (int i = n - 2; i >= 0; --i) {
    	decreasing[i] = arr.get(i) > arr.get(i + 1)
    	? decreasing[i + 1] + 1
    	: 1;
    }
    
    long candiesGiven = decreasing[0];
    for (int i = 1, candiesLast = decreasing[0]; i < n; ++i) {
    	candiesLast = arr.get(i) > arr.get(i - 1)
    	? Math.max(candiesLast + 1, decreasing[i])
    	: decreasing[i];
    
    	candiesGiven += candiesLast;
    }
    
    return candiesGiven;
    }