当前位置:网站首页>Bm95 points candy problem

Bm95 points candy problem

2022-06-21 17:37:00 Programmer Xiao Li

A group of children play games , Now please give out candy according to the score of the game , Requirements are as follows :

1. No matter how much each child scores , At least one candy .

2. Between any two adjacent children , Children who score more must take more candy .( If the same, there is no such restriction )

Given an array  arrarr  Represents the score array , Please return the minimum number of sweets needed .

requirement : The time complexity is  O(n)O(n)  The space complexity is  O(n)O(n)

Everyone has at least one .

Traverse once from left to right , Meet the people on the right .( Similar to a microphone , When traversing from left to right , Only care about whether it is higher than the one on your left )

Traverse once from right to left , Meet the people on the left .( Similar to a microphone , From right to left , Only care about whether it is higher than the one on your right )

    public int candy (int[] arr) {
        // write code here
        int[] result = new int[arr.length];
        
        //  At least one per person 
        for (int i = 0 ; i < result.length; i++){
            result[i] = 1;
        }
        
        //  The score on the right is higher than that on the left , One more point 
        for (int i = 1 ; i < arr.length; i++){
            if (arr[i] > arr[i-1]){
                result[i] = result[i-1] + 1;
            }
        }
        
        //  The score on the left is higher than that on the right 
        for (int i = arr.length - 1; i > 0; i--){
            if (arr[i - 1] > arr[i]){
                result[i - 1] = result[i-1] < result[i] + 1 ? result[i] + 1 : result[i-1];
            }
        }
        
        int sum = 0;
        for (int i = 0 ; i < result.length; i++){
            sum += result[i];
        }
        
        return sum;
    }

notes : From right to left , It should be noted that the left side is more likely to get candy than the right side .

原网站

版权声明
本文为[Programmer Xiao Li]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/172/202206211522219210.html