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
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值