Interview Question Array Partition I

Last update: 5/6/2017 9:49:00 PM

By Fatih KABAKCI

Problem #561 - Array Partition I

Description: Given an array of 2n integers, your task is to group these integers into n pairs of integer, say (a1, b1), (a2, b2), ..., (an, bn) which makes sum of min(ai, bi) for all i from 1 to n as large as possible.

Example 1:
Input: [1,4,3,2]

Output: 4
Explanation: n is 2, and the maximum sum of pairs is 4.
Note:
n is a positive integer, which is in the range of [1, 10000].
All the integers in the array will be in the range of [-10000, 10000]..

Difficulty: Easy

Solution in Java

package com.fatihkabakci.Easy.ArrayPartitionI;import java.util.Arrays;/***@authorfkabakci * Problem Description: Given an array of 2n integers, your task is to group * these integers into n pairs of integer, say (a1, b1), (a2, b2), ..., (an, bn) * which makes sum of min(ai, bi) for all i from 1 to n as large as possible.** Example 1:* Input: [1,4,3,2]** Output:4* Explanation: n is 2, and the maximum sum of pairs is 4.** Note:n is a positive integer, which is in the range of [1,10000].* All the integers in the array will be in the range of [-10000,10000].* Solution:*1. Sort the array to discriminate later on easily the elements that are closest to the max element* in their groups.** For example, lets consider above the case that is 1234**3 is the closest one to 4.*1 is the closest one to 2.**1+3 = 4 is largest value that is among the sum of the min pairs. */publicclass Solution {
publicint arrayPairSum(int[] nums) {
Arrays.sort(nums);
int n = nums.length, sum = 0;
for(int i = n - 1; i > 0; i-=2) {
sum += Math.min(nums[i], nums[i - 1]);
}
return sum;
}
}

A programming language is a formal constructed language designed to communicate instructions to a machine, particularly a computer. It can be used to create programs to control the behavior of a machine.
Java,C,
C++,C#

Computer hardware is the collection of physical elements that constitutes a computer system. Computer hardware refers to the physical parts or components of a computer such as the monitor, memory, cpu.

Web development is a broad term for the work involved in developing a web site for the Internet or an intranet. Html,Css,JavaScript,ASP.Net,PHP are one of the most popular technologies.
J2EE,Servlet,
JSP,JSF,
ASP

Mobile application development is the process by which application software is developed for low-power handheld devices, such as personal digital assistants, enterprise digital assistants or mobile phones.
J2ME

A computer network or data network is a telecommunications network that allows computers to exchange data. In computer networks, networked computing devices pass data to each other along data connections.

An operating system is software that manages computer hardware and software resources and provides common services for computer programs. The OS is an essential component of the system software in a computer system.
Linux,Windows