[GeeksForGeeks] Find the largest pair sum in an unsorted array

Given an unsorted array, find the largest pair sum.

Solution 1. O(n*logn) runtime, using sorting

Solution 2. O(n) runtime, using heapify (max priority queue)

Option 1. Use Java priority queue API, easy to implement but uses O(n) extra memory.

Option 2.  Since we are given an array, heapify the array to a max pq. This does not use extra memory.

Heapify takes O(n) runtime;

delete the max value from the heapified array takes O(logn) runtime as we need to percolate down the

new head element.

 1 public class Solution {
 2     public int findLargestPair(int[] A){
 3         if(A == null || A.length <= 1){
 4             return Integer.MIN_VALUE;
 5         }
 6         heapify(A);
 7         int firstMax = A[0], secondMax = 0;
 8         A[0] = A[A.length - 1];
 9         percolateDown(A, A.length - 1, 0);
10         secondMax = A[0];
11         return firstMax + secondMax;
12     }
13     private void heapify(int[] A){
14         for(int i = A.length / 2 - 1; i >= 0; i--){
15             percolateDown(A, A.length, i);
16         }
17     }
18     private void percolateDown(int[] A, int len, int idx){
19         int maxIdx = idx;
20         int leftChildIdx = 2 * idx + 1;
21         int rightChildIdx = 2 * idx + 2;
22         if(leftChildIdx < len && A[leftChildIdx] > A[maxIdx]){
23             maxIdx = leftChildIdx;
24         }
25         if(rightChildIdx < len && A[rightChildIdx] > A[maxIdx]){
26             maxIdx = rightChildIdx;
27         }
28         if(maxIdx != idx){
29             int temp = A[idx];
30             A[idx] = A[maxIdx];
31             A[maxIdx] = temp;
32             percolateDown(A, len, maxIdx);
33         }
34     }
35 }

Solution 3. O(n) runtime, O(1) space, scan the input array once and upate the largest and second largest values along the way.

 1 public int findLargestPair(int[] A){
 2     if(A == null || A.length <= 1){
 3         return Integer.MIN_VALUE;
 4     }
 5     int firstMax = Math.max(A[0], A[1]);
 6     int secondMax = Math.min(A[0], A[1]);
 7     for(int i = 2; i < A.length; i++){
 8         if(A[i] >= firstMax){
 9             secondMax = firstMax;
10             firstMax = A[i];
11         }
12         else if(A[i] > secondMax){
13             secondMax = A[i];
14         }
15     }
16     return firstMax + secondMax;
17 }
时间: 2024-10-09 04:38:16

[GeeksForGeeks] Find the largest pair sum in an unsorted array的相关文章

uva12546. LCM Pair Sum

uva12546. LCM Pair Sum One of your friends desperately needs your help. He is working with a secret agency and doing some encoding stuffs. As the mission is confidential he does not tell you much about that, he just want you to help him with a specia

good article————K’th Smallest/Largest Element in Unsorted Array | Set 2 (Expected Linear Time)

这是本人在研究leetcode中Median of Two Sorted Arrays一题目的时候看到一篇文章,觉得非常好,其中对快速排序重新实现. 文章来源于http://www.geeksforgeeks.org/这个网站. We recommend to read following post as a prerequisite of this post. K'th Smallest/Largest Element in Unsorted Array | Set 1 Given an ar

The XOR Largest Pair(Tire字典树应用)

题目链接:传送门 思路:建立一个32位的字典树,对每一个要插入的数字查找它异或的最大值(就是尽量全部二进制的值都相反), 然后获得两个数异或的最大值. #include<iostream> #include<cstdio> #include<cstring> using namespace std; const int maxn = 1e5+10; int ch[maxn*32][2],tot; void Insert(int x) { int i,u=1,c; for

【Trie】The XOR Largest Pair

[题目链接] https://loj.ac/problem/10050 [题意] 给出n个数,其中取出两个数来,让其异或值最大. [题解] 经典的01字典树问题. 首先需要把01字典树建出来. 然后对于每一个串都跑一遍.如果存在当前位 不同的 节点,就往那里跑,否则顺着跑. 一切尽在代码中. [代码] 1 #include<bits/stdc++.h> 2 using namespace std; 3 typedef long long ll; 4 const int N = 1e5+10;

The XOR Largest Pair

https://loj.ac/problem/10050 题目描述 ??给出\(n\)个整数,求选出两个数使它们的异或值最大. 思路 ??解决异或问题也是字典树的常用作用之一.我们考虑对于一个数\(x\),我们如何求出它的异或值最大的另一个数.异或的定义是每一位相同为\(0\),不同为\(1\),所以我们只需要查找二进制下每一位都和\(x\)不同的数.而这道题实际给定范围,那么我们可以考虑建一棵字典树,存二进制每一位的值,对于查找的数\(x\),我们只需要从高位往低位枚举,尽量找每一位与这个数这

The XOR Largest Pair之二

Description今天小W用了1s不到的时候完成了这样一个题:在给定的N个整数 A_1,A_2,…,A_N中选出两个进行异或运算,得到的结果最大是多少?正当他志得意满时,L老师亮出了另一个题:给你1000个数字a1到a1000,从其中选出三个数字ai,aj,ak(1<=i,j,k<=1000,且i,j,k互不相同)满足(ai+aj)xor ak的值最大小W顿时迷茫了......... Input第一行给出数字N,接下来N行,每行一个数字Output如题Sample Input41234Sa

[CareerCup] 18.12 Largest Sum Submatrix 和最大的子矩阵

18.12 Given an NxN matrix of positive and negative integers, write code to find the submatrix with the largest possible sum. 这道求和最大的子矩阵,跟LeetCode上的Maximum Size Subarray Sum Equals k和Maximum Subarray很类似.这道题不建议使用brute force的方法,因为实在是不高效,我们需要借鉴上面LeetCode

[LeetCode][Java] Binary Tree Maximum Path Sum

题目: Given a binary tree, find the maximum path sum. The path may start and end at any node in the tree. For example: Given the below binary tree, 1 / 2 3 Return 6. 题意: 给定一棵二叉树,找出最大得路径和. 路径的起始和结束位置可以是树中的任意节点. 比如, 给定如下的一棵二叉树 1 / 2 3 返回  6. 算法分析: 1) Rec

[email&#160;protected] Minimum sum partition (Dynamic Programming)

http://www.practice.geeksforgeeks.org/problem-page.php?pid=166 Minimum sum partition Given an array, the task is to divide it into two sets S1 and S2 such that the absolute difference between their sums is minimum. Input: The first line contains an i