leetcode gas-station【最大序列变形】
来源:互联网 发布:gta5捏脸数据男欧美 编辑:程序博客网 时间:2024/06/03 19:43
There are N gas stations along a circular route, where the amount of gas at stationi isgas[i].
You have a car with an unlimited gas tank and it costscost[i]of gas to travel from stationi 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.
Note:The solution is guaranteed to be unique
百度题号,说到是最大序列的变形,然后自己想:
最大序列咋求的?从开头开始算累加和,发现小于0,前面都不要了,从当前位置重新加和,因为某段和是负数说明这段不会对于最大序列做贡献。
这个题也一样,某段如果是负数说明放结尾,要么就是根本没有可行解。
从0开始(这点我得吐槽一下,leetcode什么玩意,连个示例都没有,都不知道0开始还是1开始)
三个变量pos,sum,tmp分别表示开始点,总和,当前段的和。
如果发现某一段和是负数就清零tmp,pos换成下一个点
最后不要忘记sum+=tmp
判断sum值是否大于等于0
class Solution {public: int canCompleteCircuit(vector<int> &gas, vector<int> &cost) { int num=gas.size(); int sum=0,tmp=0; int pos=0; for(int i=0;i<num;i++) { tmp+=gas[i]; tmp-=cost[i]; if(tmp<0) {pos=i+1;sum+=tmp;tmp=0;} } sum+=tmp; if(sum>=0)return pos; else return -1; }};
0 0
- 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
- leetcode Gas Station
- 【Leetcode】Gas Station
- LeetCode | Gas Station
- LeetCode之Gas Station
- Leetcode: Gas Station
- LeetCode OJ:Gas Station
- [LeetCode]134.Gas Station
- js数组的操作
- Servlet中Response对象应用2(输出随机验证码图片)
- Sqlserver 链接服务器和同义词
- MapReduce小作业
- string
- leetcode gas-station【最大序列变形】
- Android中的GraphicBuffer同步机制-Fence
- vim插件和配置
- 杭电OJ 1003 Max Sum
- JS学习-js内置对象
- Android,JCVideoPlayerStandard,节操,视频播放
- Idea Spring boot+Maven 打包war 发布 外部tomcat
- 如何用一台电脑绑定多个github账户
- Linux环境下加载Spring的问题