Open youngyangyang04 opened 3 months ago
int temp = 0, sum = 0, start = 0;
for (int i = 0; i < gas.length; i++) {
temp += gas[i] - cost[i];
sum += gas[i] - cost[i];
if (temp < 0) {
temp = 0;
start = i + 1;
}
}
if (sum < 0) return -1;
return start;
// 例: gas = [2,5,2,3,5], cost = [1,2,8,2,4], start = 0
i = 0: temp = 0 + 1 = 1(不重计), sum = 0 + 1 = 1
i = 1: temp = 1 + 3 = 4(不重计), sum = 1 + 3 = 4
i = 2: temp = 4 + -6 = -2(要重计), sum = 4 + -6 = -2, temp = 0, start = 3
i = 3: temp = 0 + 1 = 1(不重计), sum = -2 + 1 = -1
i = 4: temp = 1 + 1 = 2(不重计), sum = -1 + 1 = 0 // sum >= 0 存在解
start = i + 1 不会越界吗?
https://www.programmercarl.com/0134.%E5%8A%A0%E6%B2%B9%E7%AB%99.html