day30 贪心算法04

85 阅读2分钟

134. 加油站

文章讲解

思路:

画图,sum+=gas[i]-cost[i],然后找到最低点的下一个位置就是
total代表途中的油量,最低点后油量开始变多了,

image.png

class Solution:
    def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
        total = 0
        min_val = 0
        start = 0

        for i in range(len(gas)):
            total += (gas[i] - cost[i])
            if total < min_val:
                min_val = total
                start = i + 1
        
        if total<0:
            return -1
        return 0 if start == len(gas) else start

135. 分发糖果

文章讲解

思路:

1 从左往右,如果r[i]>r[i-1] left[i]=left[i-1] + 1  left[0]=1
2 从右往左,如果r[i]>r[i+1] right[i] = right[i+1] + 1 right[n-1]=1
class Solution:
    def candy(self, ratings: List[int]) -> int:
        if not ratings: return 0
        n = len(ratings)
        left = [1]  * len(ratings)
        # right = [1]  * len(ratings)       
        right = 1

        result = 0 # 最小糖果数量

        # 左规则
        for i in range(1, len(ratings)):
            if ratings[i] > ratings[i-1]:
                left[i] = left[i-1] + 1

        # 右规则
        for i in range(n-1,-1,-1):
            if i<n-1 and  ratings[i] > ratings[i+1]:
                # right[i] = right[i+1] + 1
                right += 1
            else:
                right = 1
            # result += max(left[i], right[i])
            result += max(left[i], right)


        return result

860. 柠檬水找零

文章讲解

思路:

情况一:账单是5,直接收下。
情况二:账单是10,消耗一个5,增加一个10
情况三:账单是20,优先消耗一个10和一个5,如果不够,再消耗三个5

class Solution:
    def lemonadeChange(self, bills: List[int]) -> bool:
        five, ten, twenty = 0, 0, 0
        for bill in bills:
            if bill == 5:
                five += 1
            elif bill == 10:
                # 需要一个5
                if five > 0:
                    five -= 1
                    ten += 1
                else:
                    return False
            elif bill == 20:
                # 两种情况:1 取1个10和一个5(10只能给20找零,优先使用); 2 取3个5
                if ten>0 and five > 0:
                    ten -= 1
                    five -= 1
                    twenty += 1
                elif five>=3:
                    five -= 3
                    twenty += 1
                else:
                    return False
        return True

406. 根据身高重建队列

文章讲解

思路:

1 先按照升高h降序,个数k升序排序 
2 迭代每个人,按照k作为索引插入

class Solution:
    def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:
        people.sort(key = lambda x: (-x[0], x[1]))
        queue = []
        for p in people:
            queue.insert(p[1], p)
        
        return queue