华为OD机试真题 - 贪吃的猴子

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int num = Integer.parseInt(in.nextLine());
        int[] nums = Arrays.stream(in.nextLine().split(" ")).mapToInt(Integer::parseInt).toArray();
        int times = Integer.parseInt(in.nextLine());
        System.out.println(getResult(nums, times));
    }

    public static int getResult(int[] nums, int times) {
        int[] left = new int[nums.length];
        int[] right = new int[nums.length];
        int leftSum = 0;
        int rightSum = 0;
        for (int i = 0; i < nums.length; i++) {
            leftSum += nums[i];
            left[i] = leftSum;
            rightSum += nums[nums.length - 1 - i];
            right[i] = rightSum;
        }
        int ans = 0;
        for (int i = -1, j = times - 1; i < times; i++,j--) {
            int l = 0;
            int r = 0;
            if (i >= 0)
                l = left[i];
            if (j >= 0)
                r = right[j];
            ans = Math.max(ans, r + l);
        }
        return ans;
    }
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务