Wednesday, July 3, 2024
HomeData ModellingData Structure & AlgorithmFind maximum value of the last element after reducing the array with...

Find maximum value of the last element after reducing the array with given operations

Given an array arr[] of N elements, you have to perform the following operation on the given array until the array is reduced to a single elements, 
 

  1. Choose two indices i and j such that i != j.
  2. Replace arr[i] with arr[i] – arr[j] and remove arr[j] from the array.

The task is to maximize and print the value of the last remaining element of the array.
Examples: 
 

Input: arr[] = {20, 3, -15, 7} 
Output: 45 
Step 1: We can remove 7 and replace -15 with -22. 
step 2: We can remove 3 and replace -22 with -25. 
step 3: We can remove -25 and replace 20 with 45. 
So 45 is the maximum value that we can get.
Input: arr[] = {5, 4, 6, 2} 
Output: 13 
 

 

Approach: In order to maximize the value of the last remaining element, there are three cases: 
 

  1. Array has negative as well as positive numbers: First we will subtract all positive numbers (except one) from negative numbers. After this, we will only be left with a single positive and a single negative number. Now, we will subtract that negative number from the positive one which will yield a positive number at last as a result. So, in this case, the result is the sum of absolute values of the array elements.
  2. Array contains only positive numbers: First we find the smallest number and then subtract all positive numbers from it except one positive number. After this we get just one positive number and one negative number, now we will subtract the negative number from that positive one which will yield a positive number at last as a result. Here we can observe that the smallest 
    number has vanished and also the value is basically cut out from next greater element which is different from case 1. So, in this case the result is the sum of absolute values of array elements – 2 * minimum element.
  3. Array contains only negative numbers: First we find the largest number and then subtract all negative number from it except one negative number. After this we get just one negative number and one positive number, now we will subtract the negative number from that positive one which will yield a positive number at last as a result. Here we can observe that the largest number has vanished and also the value is basically cut out from next greater element which is different from case 1. So in this case the result is the sum of the absolute values of array elements – 2 * absolute of largest element. Here we take largest as absolute of largest is smallest in case of negative number.

Below is the implementation of the above approach: 
 

C++




// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to return the maximized value
int find_maximum_value(int a[], int n)
{
    int sum = 0;
    int minimum = INT_MAX;
    int pos = 0, neg = 0;
 
    for (int i = 0; i < n; i++) {
 
        // Overall minimum absolute value
        // of some element from the array
        minimum = min(minimum, abs(a[i]));
 
        // Add all absolute values
        sum += abs(a[i]);
 
        // Count positive and negative elements
        if (a[i] >= 0)
            pos += 1;
        else
            neg += 1;
    }
 
    // Both positive and negative
    // values are present
    if (pos > 0 && neg > 0)
        return sum;
 
    // Only positive or negative
    // values are present
    return (sum - 2 * minimum);
}
 
// Driver code
int main()
{
    int a[] = { 5, 4, 6, 2 };
    int n = sizeof(a) / sizeof(a[0]);
 
    cout << find_maximum_value(a, n);
 
    return 0;
}


Java




// Java implementation of the approach
import java.io.*;
 
class GFG
{
     
    // Function to return the maximized value
    static int find_maximum_value(int a[], int n)
    {
        int sum = 0;
        int minimum = Integer.MAX_VALUE;
        int pos = 0, neg = 0;
     
        for (int i = 0; i < n; i++)
        {
     
            // Overall minimum absolute value
            // of some element from the array
            minimum = Math.min(minimum, Math.abs(a[i]));
     
            // Add all absolute values
            sum += Math.abs(a[i]);
     
            // Count positive and negative elements
            if (a[i] >= 0)
                pos += 1;
            else
                neg += 1;
        }
     
        // Both positive and negative
        // values are present
        if (pos > 0 && neg > 0)
            return sum;
     
        // Only positive or negative
        // values are present
        return (sum - 2 * minimum);
    }
     
    // Driver code
    public static void main (String[] args)
    {
         
        int []a = { 5, 4, 6, 2 };
        int n = a.length;
     
        System.out.println(find_maximum_value(a, n));
    }
}
 
// This code is contributed by ajit


Python




# Python3 implementation of the approach
 
# Function to return the maximized value
def find_maximum_value(a, n):
     
    sum = 0
    minimum = 10**9
    pos = 0
    neg = 0
 
    for i in range(n):
 
        # Overall minimum absolute value
        # of some element from the array
        minimum = min(minimum, abs(a[i]))
 
        # Add all absolute values
        sum += abs(a[i])
 
        # Count positive and negative elements
        if (a[i] >= 0):
            pos += 1
        else:
            neg += 1
 
    # Both positive and negative
    # values are present
    if (pos > 0 and neg > 0):
        return sum
 
    # Only positive or negative
    # values are present
    return (sum - 2 * minimum)
 
# Driver code
 
a= [5, 4, 6, 2]
n = len(a)
 
print(find_maximum_value(a, n))
 
# This code is contributed by mohit kumar 29


C#




// C# implementation of the approach
using System;
 
class GFG
{
 
    // Function to return the maximized value
    static int find_maximum_value(int []a, int n)
    {
        int sum = 0;
        int minimum = int.MaxValue;
        int pos = 0, neg = 0;
     
        for (int i = 0; i < n; i++)
        {
     
            // Overall minimum absolute value
            // of some element from the array
            minimum = Math.Min(minimum, Math.Abs(a[i]));
     
            // Add all absolute values
            sum += Math.Abs(a[i]);
     
            // Count positive and negative elements
            if (a[i] >= 0)
                pos += 1;
            else
                neg += 1;
        }
     
        // Both positive and negative
        // values are present
        if (pos > 0 && neg > 0)
            return sum;
     
        // Only positive or negative
        // values are present
        return (sum - 2 * minimum);
    }
     
    // Driver code
    static public void Main ()
    {
        int []a = { 5, 4, 6, 2 };
        int n = a.Length;
     
        Console.WriteLine(find_maximum_value(a, n));
    }
}
 
// This code is contributed by AnkitRai01


Javascript




<script>
// javascript implementation of the approach
 
    // Function to return the maximized value
    function find_maximum_value(a , n) {
        var sum = 0;
        var minimum = Number.MAX_VALUE;
        var pos = 0, neg = 0;
 
        for (i = 0; i < n; i++) {
 
            // Overall minimum absolute value
            // of some element from the array
            minimum = Math.min(minimum, Math.abs(a[i]));
 
            // Add all absolute values
            sum += Math.abs(a[i]);
 
            // Count positive and negative elements
            if (a[i] >= 0)
                pos += 1;
            else
                neg += 1;
        }
 
        // Both positive and negative
        // values are present
        if (pos > 0 && neg > 0)
            return sum;
 
        // Only positive or negative
        // values are present
        return (sum - 2 * minimum);
    }
 
    // Driver code
        var a = [ 5, 4, 6, 2 ];
        var n = a.length;
 
        document.write(find_maximum_value(a, n));
 
// This code is contributed by todaysgaurav
</script>


Output: 

13

 

Time Complexity: O(N)

Auxiliary Space: O(1)
 

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments