ByteDance has N workshops in Beijing
Title description:
The first question. Byte Bounce has N work zones in Beijing, forming a ring. Bytebus is a commuter car to and from each work zone, driving in the order of the work zones, of which the ith work zone has gasoline gas [i] liters. You have a Bytebus with unlimited fuel tank capacity. From the i-th work zone to the i + 1th work zone, you need to consume gasoline cost [i] liters. You start from one of the work areas, and the fuel tank is empty at the beginning. If you can travel around the ring road for a week, then return to the number of the work area at departure, otherwise return -1.
Examples:
输入:
gas = [1,2,3,4,5]
cost = [3,4,5,1,2]
输出:
3
thought:
I don't know what kind of thinking this is. See the note below for details. Time complexity O (n).
Code:
static int staNum(int[] gas, int[] cost) {
int len = gas.length;
int nowLeft=0;
int preCost=0,flag=0;//flag标记起点下标
for(int i=0;i<len;++i){
nowLeft+= gas[i] - cost[(i+1+len)%len];
if(nowLeft<0){//此时油量为负数
preCost+=nowLeft;//累计负的油量
nowLeft=0;//清零重新开始
flag=i+1;//表示将下一个工区作为起点
}
}
if(nowLeft+preCost<0){//总剩余油量为负数返回-1
return -1;
}
return flag+1;
}
In addition, I discussed it with my classmates yesterday, and I feel that the subject ’s understanding of i is a bit ambiguous. For example, from gas [0] to gas [1], the amount of oil to be consumed is cost [0] or cost [1]. The code is based on cost [1]. If cost [0], then, a more straightforward, the code cost [(i + 1 + len )% len] replaced cost [I] , and finally return flag on the line. But the problem is not big, the idea is the same.
This is a question in the face script that I saw on the cattle guest yesterday. If the answer is wrong, the officials can be outspoken ~