[leetcode][贪心] Gas Station

题目:

There are N gas stations along a circular route, where the amount of gas at station i is gas[i].

You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to its next station (i+1). You begin the journey with an empty tank at one of the gas stations.

Return the starting gas station's index if you can travel around the circuit once, otherwise return -1.

class Solution {
public:
//如果我是司机,我会想要从一个加油站出发,一路向前使自己储存的油量为最大,以被在后面耗油较多时也能有油可用,我们只要找到使储油量达到峰值的那个其实加油站
//于是,问题转化为求最大和的连续子数组。
//非循环数组的最大和的连续子数组可用用动态规划求得(maxSum)。
//什么时候符合条件的子数组需要首尾相连呢?——中间有一段连续子数组,其和为负且绝对值最大
//原数组去掉中间这段子数组后的值为total - minSum
//那么,循环数组的连续子数组的最大和为max(maxSum, total-minSum)
    int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
        if(gas.size() != cost.size() || gas.empty()) return -1;
        int diff0 = gas[0]-cost[0];
        int maxStart = 0;//最大和连续子序列的起始位置
        int maxSum = diff0;//连续子序列最大和
        int minEnd = 0;//最小子连续序列的结束位置
        int minSum = diff0;//连续子序列最小和
        int total = diff0;//gas和cost所有对应元素之差的和
        
        int sum1 = diff0;//当前连续序列的和,用于查找最大和连续子序列
        int sum2 = diff0;//当前连续序列的和,用于查找最小和连续子序列
        int start1 = 0;//当前连续序列的起始位置,用于查找最大和连续子序列的起始位置
        int end2 = 0;//当前连续序列的结束位置, 用于查找最小和连续子序列的结束位置
        //求循环数组的最大连续子序列
        for(int i = 1; i < gas.size(); ++i){
            int diff = gas[i]-cost[i];
            total += diff;
             //查找最大连续子序列的和和起始位置
            if(sum1 < 0){
                sum1 = diff;
                start1 = i;
            }
            else sum1 += diff;
            if(sum1 > maxSum){
                maxSum = sum1;
                maxStart = start1;
            }
            //查找最小连续子序列的和和结束位置
            if(sum2 > 0){
                sum2 = diff;
                end2 = i;
            }
            else sum2 += diff;
            if(sum2 < minSum){
                minSum = sum2;
                minEnd = i;
            }
        }
        //如果total小于0,则不可能走完一圈
        if(total < 0) return -1;
        //循环数组的最大连续子序列为max(maxSum, total-minSum)
        return maxSum >= total - minSum ? maxStart : minEnd+1;
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值