牛客网:获得最多的奖金(双指针)

牛客网:获得最多的奖金(双指针)

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)

有三种情况:

  1. leftValue == rightValue

    记录此时两者的值为max

  2. leftValue > rightValue

    end指针减1,rightValue = rightValue + arr[end]

  3. 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);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值