[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
- [leetcode][贪心] Gas Station
- leetcode---gas-station---贪心
- leetCode #134 Gas Station 贪心
- leetcode贪心算法:Gas Station
- [leetcode] 134 Gas Station(经典dp || 贪心)
- [LeetCode]Gas Station 最大子序列和,贪心
- leetcode -- Gas Station -- 跟jump game像,重点--贪心
- leetcode贪心之gas-station条件决定答案
- LeetCode:Gas Station
- [LeetCode] Gas Station
- [leetcode]Gas Station
- Leetcode: Gas Station
- LeetCode:Gas Station
- [LeetCode] Gas Station
- leetcode Gas Station
- [LeetCode]Gas Station
- LeetCode 之 Gas Station
- leetcode Gas Station
- 发布3633快速接单软件V1.2
- php异常处理—异常的基本用法
- android studio 使用以及常出现的问题
- 为GCD队列绑定NSObject类型上下文数据-利用__bridge_retained(transfer)转移内存管理权
- 南京大学<软件测试>笔记
- [leetcode][贪心] Gas Station
- JSP&Servlet
- 悬浮窗onTouch和onCLick的冲突
- Javascript异步编程的4种方法
- SpringMVC实现RESTful风格
- 大数据
- C/C++文件中函数互相调用
- html定位
- KeilMDK 编译报错:error: #268: declaration may not appear after executable statement in block