Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Minimum possible sum of array elements after performing the given operation
Next article icon

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

Last Updated : 31 May, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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)
 



Next Article
Minimum possible sum of array elements after performing the given operation

S

souradeep
Improve
Article Tags :
  • Analysis of Algorithms
  • Arrays
  • DSA
  • Greedy
  • Mathematical
Practice Tags :
  • Arrays
  • Greedy
  • Mathematical

Similar Reads

  • Find the index of the array elements after performing given operations K times
    Given an array arr[] and an integer K, the task is to print the position of the array elements, where the ith value in the result is the index of the ith element in the original array after applying following operations exactly K times: Remove the first array element and decrement it by 1.If it is g
    7 min read
  • Reduce the array to a single element with the given operation
    Given an integer N and an array arr containing integers from 1 to N in a sorted fashion. The task is to reduce the array to a single element by performing the following operation: All the elements in the odd positions will be removed after a single operation. This operation will be performed until o
    4 min read
  • Minimum element left from the array after performing given operations
    Given an array arr[] of N integers, the task is to remove the elements from both the ends of the array i.e. in a single operation, either the first or the last element can be removed from the current remaining elements of the array. This operation needs to be performed in such a way that the last el
    3 min read
  • Maximize the value left after reducing the Arrays based on given conditions
    Given three arrays arr1[], arr2[] and arr3[] of integers, the task is to find the maximum value left in an array after performing the following operation, where in each operation: Select an element (y) from one array and remove that from the array.Subtract y from another element(x) of another array.
    8 min read
  • Minimum possible sum of array elements after performing the given operation
    Given an array arr[] of size N and a number X. If any sub array of the array(possibly empty) arr[i], arr[i+1], ... can be replaced with arr[i]/x, arr[i+1]/x, .... The task is to find the minimum possible sum of the array which can be obtained. Note: The given operation can only be performed once.Exa
    9 min read
  • Find the minimum value of K required to remove all elements from the array in at most M operations
    Given array A[] of size N and integer M, Perform the following operation until the array becomes empty. Choose K and the pick first K elements of array A[]. In one operation subtract all these chosen K elements by 1 if any element becomes zero that element will be deleted and it will be replaced by
    13 min read
  • Minimum length of the reduced Array formed using given operations
    Given an array arr of length N, the task is to minimize its length by performing following operations: Remove any adjacent equal pairs, ( i.e. if arr[i] = arr[i+1]) and replace it with single instance of arr[i] + 1.Each operation decrements the length of the array by 1.Repeat the operation till no m
    10 min read
  • Minimum number of given operations required to reduce the array to 0 element
    Given an array arr[] of N integers. The task is to find the minimum number of given operations required to reduce the array to 0 elements. In a single operation, any element can be chosen from the array and all of its multiples get removed including itself.Examples: Input: arr[] = {2, 4, 6, 3, 4, 6,
    6 min read
  • Find position of the leader element in given Array with given operations
    Given an array arr[]. The task is to find the position of the leader element in arr[]. The leader element is the one, which can remove all other elements in the array using the below operations. If arr[i] > arr[i + 1], It removes the (i+1)th element and increment their value by 1 and decrease the
    8 min read
  • Find the modified array after performing k operations of given type
    Given an array arr[] of n integers and an integer K. In one operation every element of the array is replaced by the difference of that element and the maximum value of the array. The task is to print the array after performing K operations.Examples: Input: arr[] = {4, 8, 12, 16}, k = 2 Output: 0 4 8
    10 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences