Runtime: O(n) Space: O(1), Java Solution, Easy to Read, Beats 97.68%


  • 0
    N
     /* 
     * We will find the max sum of all minimum pairs by
     * finding the minimum of consecutive value pairs.
     * Runtime complexity is O(s), where s is the array size.
     * Space complexity is O(1)
     */
    public class Solution {
        public int arrayPairSum(int[] nums) {
            // Constants used to create the hash table and function
            final int HASH_SIZE = 20001;
            final int HASH_ADD = 10000;
            
            /* 
             * This hash table re-presents num array by keeping
             * a count of the numbers in the array.
             * Example: nums = [3, 3, 3, 3]. Means that the value 4 is stored at
             * hashTable[3 + HASH_ADD].
             */
            int[] hashTable = new int[HASH_SIZE];
            for (int i = 0; i < nums.length; i++) {
                hashTable[nums[i] + HASH_ADD] += 1;
            }
            
            // Sums the minimum of consecutive value pairs
            int sum = 0;
            boolean addFlag = true;
            for (int i = 0; i < HASH_SIZE; i++) {
                for (int j = hashTable[i]; j > 0; j--) {
                    if (addFlag) {
                        // Adds the reverse of the 1-1 hash function
                        sum += (i - HASH_ADD);
                    }
                    addFlag = !addFlag;
                }
            }
            
            return sum;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.