牛客网:获得最多的奖金(双指针)
1.题目链接
https://www.nowcoder.com/practice/247f7bd088764aefa7474cff27489095?tpId=98&tqId=32839&tPage=1&rp=1&ru=/ta/2019test&qru=/ta/2019test/question-ranking
2.分析
用头指针begin和尾指针end,两边向中间靠拢
左边部分的总和为leftValue(0 ~ begin)
,右边部分的总和为rightValue(end ~ lengh - 1)
有三种情况:
-
leftValue == rightValue
记录此时两者的值为max
-
leftValue > rightValue
end指针减1,rightValue = rightValue + arr[end]
-
leftValue < rightValue
begin指针加1,leftValue = leftValue + arr[begin]
3.代码
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
int[] arr = new int[num];
for(int i = 0; i < num; i++){
arr[i] = sc.nextInt();
}
int begin = -1;
int end = arr.length;
long leftValue = 0;
long rightValue = 0;
long max = 0;
while(begin != end){
if(leftValue == rightValue){
max = leftValue;
leftValue += arr[++begin];
}else if(leftValue > rightValue){
end--;
rightValue += arr[end];
}else if(leftValue < rightValue){
begin++;
leftValue += arr[begin];
}
}
System.out.println(max);
}
}