LeetCode Candy Greedy Algorithm(golang)

Problem
在这里插入图片描述
Analysis Process
Rule definition:
Suppose student A and student B are adjacent to each other, and AAis to the left of B;
Left rule: when ratings A>ratings A ,B has more sugar than A,
Right rule: when ratings A>ratings B ,A has more sugar than B

Among adjacent students, students with high scores must receive more candy equivalent to all students meeting the left rule and meeting the right rule

1.First, go through student grade ratings from left to right, give sugar according to the following rules, and record in left
Give all the students a candy first
If ratings i > ratings i-1 , then student i has one more sugar than student i-1
If ratings i <= Ratings i-1, then the amount of sugar in student i will remain unchanged

2.Similarly, under this rule, students’ grades are traversed from right to left and recorded in right, so as to ensure that all students’ sugar quantity meets the right rule

Code

func candy(ratings []int) int {
    l := len(ratings) 
    if l == 0 {
        return 0
    }                    //determine whether the array is empty or only has one num
    if l == 1 {
        return 1
    }
    var res []int
    res = append(res, 1)
    for i := 1; i < l; i++ {
        if ratings[i] > ratings[i - 1] {
            res = append(res, res[i - 1] + 1)      
        } else {
            res = append(res, 1)
        }
    }                                         //from left to right
    var sum = res[l - 1]
    for i := l - 2; i >= 0; i-- {
        if ratings[i] > ratings[i + 1] && res[i] <= res[i + 1] {
            res[i] = res[i + 1] + 1                //from right to left
        }
        sum = sum + res[i]                        //sum
    }
    return sum
}

猜你喜欢

转载自blog.csdn.net/qq_46595591/article/details/107763890