Join Regular Classroom : Visit ClassroomTech

Number Puzzle | Coding Problem Solve | codewindow.in

Number Puzzle

Given a set of numbers, one can arrange them in any order but must pay a penalty equal to the sum of the absolute differences between adjacent numbers.
Return the minimum penalty that must be paid.

Input Specification:
input1:
Length of an integer array of numbers (2<=input1<=1000)
input2:
Integer array (1<=input2[i]<=10000)

Output specification:
Return the minimum penalty.

Example:
Input1: 3
Input2: 1 3 2

Output: 2

Explanation:
The order that incurs the minimum penalty is 1,2,3. The penalty is abs(2-1)+ abs(3-2)=2.

Example:
Input1: 4
Input2: 1 6 -2 4

Output: 8

Explanation: The order that incurs the minimum penalty is -2,1,4,6. The penalty is abs(6-4) + abs(1-(-2)) = 2+3+3=8

Coding Solve:

// Solution in Java
import java.util.*;
import java.lang.*;
import java.io.*;

class Codewindow
{
	public static void main (String[] args) throws Exception
	{
		// your code goes here
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		int n = Integer.parseInt(br.readLine());
		String[] str = br.readLine().split(" ");
		int num[] = new int[n];
		
		for(int i=0; i<str.length; i++)
		    num[i] = Integer.parseInt(str[i]);
		Arrays.sort(num);
		int minPenalty = 0;
		for(int i=0; i<n-1; i++)
		    minPenalty += Math.abs(num[i] - num[i+1]);
		System.out.println(minPenalty);
	}
}
Recent Posts