[leetcode][贪心] Gas Station

来源:互联网 发布:python自动化ios开发 编辑:程序博客网 时间:2024/05/02 00:29

题目:

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