public static int distribute(final int[] ratings) {
        List<Integer> position = new ArrayList<>(ratings.length);
        // position array with position[i] = i
        for( int i = 0; i< ratings.length; i++) {
            position.add(i, i);
        }

        // sort it according to the ratings array
        Collections.sort(position, new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return Integer.compare(ratings[o1], ratings[o2]);
            }
        });

        // initialize the candies array
        int[] candies = new int[ratings.length];
        int count = 0;
        //iterate through position array from left to right
        for( int i : position) {
            // default candy value
            int c = 1;
            // if rating of i is bigger than i -1th rating
            if (i > 0 && ratings[i] > ratings[i-1]) {
                // give him one more candy among the max of any smaller child
                c = Math.max(c, candies[i-1]+1);
            }
            // if rating of i is more than i+1 element
            if (i < ratings.length - 1 && ratings[i] > ratings[i+1]) {
                // give him one more candy among the max of any smaller
                c = Math.max(c, candies[i+1]+1);
            }
            candies[i] = c;
            // keep a running count of candy
            count += c;
        }

        return count;

    }