Given an array A[] of n-elements. We need to select two adjacent elements and delete the larger of them and store smaller of them to another array say B[]. We need to perform this operation till array A[] contains only single element. Finally, we have to construct the array B[] in such a way that total sum of its element is minimum. Print the total sum of array B[]
Examples:
Input : A[] = {3, 4}
Output : 3
Input : A[] = {2, 4, 1, 3}
Output : 3
There is an easy trick to solve this question and that is always choose the smallest element of array A[] and its adjacent, delete the adjacent element and copy smallest one to array B[]. Again for next iteration we have same smallest element and any random adjacent element which is to be deleted. After n-1 operations all of elements of A[] got deleted except the smallest one and at the same time array B[] contains “n-1” elements and all are equal to smallest element of array A[].
Thus total sum of array B[] is equal to smallest * (n-1).
Implementation: Rearrange positive and negative numbers using inbuilt sort function
C++
#include <bits/stdc++.h>
using namespace std;
int minSum( int A[], int n)
{
int min_val = *min_element(A, A+n);
return (min_val * (n-1));
}
int main()
{
int A[] = { 3, 6, 2, 8, 7, 5};
int n = sizeof (A)/ sizeof (A[0]);
cout << minSum(A, n);
return 0;
}
|
Java
import java.util.Arrays;
public class GFG {
static int minSum( int [] A, int n) {
int min_val = Arrays.stream(A).min().getAsInt();
return (min_val * (n - 1 ));
}
static public void main(String[] args) {
int [] A = { 3 , 6 , 2 , 8 , 7 , 5 };
int n = A.length;
System.out.println((minSum(A, n)));
}
}
|
Python
def minSum(A):
min_val = min (A);
return min_val * ( len (A) - 1 )
A = [ 7 , 2 , 3 , 4 , 5 , 6 ]
print (minSum(A))
|
C#
using System;
using System.Linq;
public class GFG
{
static int minSum( int []A, int n)
{
int min_val = A.Min();
return (min_val * (n - 1));
}
static public void Main()
{
int []A = {3, 6, 2, 8, 7, 5};
int n = A.Length;
Console.WriteLine(minSum(A, n));
}
}
|
PHP
<?php
function minSum( $A , $n )
{
$min_val = min( $A );
return ( $min_val * ( $n - 1));
}
$A = array (3, 6, 2, 8, 7, 5);
$n = count ( $A );
echo minSum( $A , $n );
?>
|
Javascript
<script>
function minSum(A, n)
{
let min_val = Math.min(...A);
return (min_val * (n-1));
}
let A = [3, 6, 2, 8, 7, 5];
let n = A.length;
document.write(minSum(A, n));
</script>
|
Time Complexity : O(n) in finding the smallest element of the array.
Auxiliary Space: O(1)
This article is contributed by Shivam Pradhan (anuj_charm). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.