很容易想到的是暴力解法。侧重点是环形遍历数组
final int[] array = {1,2,3,4,5};
final int[] cost = { 3,4,5,1,2};
int find() {
final int j = array.length;
final int s = j - 1;
ArrayList<Integer> temp = new ArrayList<>();
for (int n = 0; n < j; n++) {
temp.add(array[n]-cost[n]);
}
for (int i = 0; i < j; i++) {
int ti = i,tj = j,tres = 0;
while (ti < tj) {
tres += temp.get(ti);
if (ti == s) {//
tj = ti;
ti = -1;
}
ti++;
}
if (tres >= 0) {
return 1;
}
}
return -1;
}
贪心解决方式
剩余油量为负数肯定是跑不完的
int find() {
final int j = array.length;
ArrayList<Integer> temp = new ArrayList<>();
for (int n = 0; n < j; n++) {
temp.add(array[n] - cost[n]);
}
return temp.stream().filter(Objects::nonNull).reduce(0,Integer::sum)>0?1:-1;
}