WOJ-74 ABC

Given an array consists of n positive integers,your task is to find the largest C which makes C=A+B. A,B,C are all in the given array.

输入格式
Standard input will contain multiple test cases. The first line of the input is an integer T (1 <= T <= 20) which is the number of test cases. For each test case,there is an integer n (3<=n<=10000) in the first line,indicating the number of elements in the array.The next line contains n positive integers.You can assume all the integers will be less then 10^9.

输出格式
For each test case,if you can find the largest integer C=A+B, output C. Notice, A and B should be different elements in the array.If there isn’t such integer C,output -1 instead.

样例输入
3
10
1 1 1 4 5 5 6 6 10 9
3
5 5 10
3
1 3 6
样例输出
10
10
-1

  • 解题思路:

1.先对所给数组进行排序,按照升序序列排序
2.双指针进行遍历

  • 直接上代码
package woj;

import java.util.Arrays;
import java.util.Scanner;

public class woj_74 {
	public static void main(String[] args) {
		Scanner cin = new Scanner(System.in);
		int n = cin.nextInt();
		cin.nextLine();
		boolean flag;
		while(n-->0) {
			int m = cin.nextInt();
			int[] nums =new int[m];
			for(int i=0;i<nums.length;i++) {
				nums[i]=cin.nextInt();
			}
			Arrays.parallelSort(nums);
			int left=0,right=0,sum=0;
			flag=true;
			for(int i=m-1;i>0;i--) {
				if(flag==false) {
					break;
				}
				sum=nums[i];
				left=0;
				right=m-2;
				while(left<right&&right>0) {
					if(nums[left]+nums[right]==sum) {
						System.out.println(sum);
						flag=false;
						break;
					}else if(nums[left]+nums[right]>sum) {
						right--;
					}else {
						left++;
					}
				}
			}
			if(flag) {
				System.out.println(-1);
			}
		}
		cin.close();
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值