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:
Maximise minimum element possible in Array after performing given operations
Next article icon

Minimum possible sum of array elements after performing the given operation

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

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.
Examples: 
 

Input: N = 3, X = 2, arr[] = {1, -2, 3} 
Output: 0.5 
Explanation: 
On selecting subarray {3} and replacing it with {1.5}, the array becomes {1, -2, 1.5}, which gives sum = 0.5
Input: N = 5, X = 5, arr[] = {5, 5, 5, 5, 5} 
Output: 5 
Explanation: 
On selecting subarray {5, 5, 5, 5, 5} and replacing it with {1, 1, 1, 1, 1}, the sum of the array becomes 5. 
 

 

Naive Approach: A naive approach is to replace all possible positive sub-arrays with the values which we get by dividing it by X and compute the sum. But the total number of sub-arrays for any given array is (N * (N + 1))/2 where N is the size of the array. Therefore, the running time of this algorithm is O(N2).
Efficient Approach: This problem can be solved efficiently in O(N) time. On observing carefully, it can be deduced that sum can be made minimum if the subarray to be replaced satisfies the following conditions: 
 

  1. The subarray should be positive.
  2. The sum of the subarray should be maximum.

Therefore, by reducing the subarray satisfying the above conditions, the sum can be made minimum. The subarray which satisfies the above conditions can be found by using a slight variation of Kadane’s algorithm. 
After finding the maximum sum of the subarray, this can be subtracted from the sum of the array to get the minimum sum. Since the maximum sum of the sub-array is being replaced with the maximum sum / X, this factor can be added to the sum which is found. That is: 
 

Minimum sum = (sumOfArr - subSum) + (subSum/ X) where sumOfArr is the sum of all elements of the array and subSum is the maximum sum of the subarray.

Below is the implementation of the above approach: 
 

CPP




// C++ program to find the minimum possible sum
// of the array elements after performing
// the given operation
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the maximum sum
// of the sub array
double maxSubArraySum(double a[], int size)
{
 
    // max_so_far represents the maximum sum
    // found till now and max_ending_here
    // represents the maximum sum ending at
    // a specific index
    double max_so_far = INT_MIN,
           max_ending_here = 0;
 
    // Iterating through the array to find
    // the maximum sum of the subarray
    for (int i = 0; i < size; i++) {
        max_ending_here = max_ending_here + a[i];
        if (max_so_far < max_ending_here)
            max_so_far = max_ending_here;
 
        // If the maximum sum ending at a
        // specific index becomes less than 0,
        // then making it equal to 0.
        if (max_ending_here < 0)
            max_ending_here = 0;
    }
    return max_so_far;
}
 
// Function to find the minimum possible sum
// of the array elements after performing
// the given operation
double minPossibleSum(double a[], int n, double x)
{
    double mxSum = maxSubArraySum(a, n);
    double sum = 0;
 
    // Finding the sum of the array
    for (int i = 0; i < n; i++) {
        sum += a[i];
    }
 
    // Computing the minimum sum of the array
    sum = sum - mxSum + mxSum / x;
 
    cout << setprecision(2) << sum << endl;
}
 
// Driver code
int main()
{
    int N = 3;
    double X = 2;
    double A[N] = { 1, -2, 3 };
    minPossibleSum(A, N, X);
}
 
 

Java




// Java program to find the minimum possible sum
// of the array elements after performing
// the given operation
class GFG{
  
// Function to find the maximum sum
// of the sub array
static double maxSubArraySum(double a[], int size)
{
  
    // max_so_far represents the maximum sum
    // found till now and max_ending_here
    // represents the maximum sum ending at
    // a specific index
    double max_so_far = Integer.MIN_VALUE,
           max_ending_here = 0;
  
    // Iterating through the array to find
    // the maximum sum of the subarray
    for (int i = 0; i < size; i++) {
        max_ending_here = max_ending_here + a[i];
        if (max_so_far < max_ending_here)
            max_so_far = max_ending_here;
  
        // If the maximum sum ending at a
        // specific index becomes less than 0,
        // then making it equal to 0.
        if (max_ending_here < 0)
            max_ending_here = 0;
    }
    return max_so_far;
}
  
// Function to find the minimum possible sum
// of the array elements after performing
// the given operation
static void minPossibleSum(double a[], int n, double x)
{
    double mxSum = maxSubArraySum(a, n);
    double sum = 0;
  
    // Finding the sum of the array
    for (int i = 0; i < n; i++) {
        sum += a[i];
    }
  
    // Computing the minimum sum of the array
    sum = sum - mxSum + mxSum / x;
  
    System.out.print(sum +"\n");
}
  
// Driver code
public static void main(String[] args)
{
    int N = 3;
    double X = 2;
    double A[] = { 1, -2, 3 };
    minPossibleSum(A, N, X);
}
}
 
// This code is contributed by Princi Singh
 
 

Python3




# Python3 program to find the minimum possible sum
# of the array elements after performing
# the given operation
 
# Function to find the maximum sum
# of the sub array
def maxSubArraySum(a, size):
 
    # max_so_far represents the maximum sum
    # found till now and max_ending_here
    # represents the maximum sum ending at
    # a specific index
    max_so_far = -10**9
    max_ending_here = 0
 
    # Iterating through the array to find
    # the maximum sum of the subarray
    for i in range(size):
        max_ending_here = max_ending_here + a[i]
        if (max_so_far < max_ending_here):
            max_so_far = max_ending_here
 
        # If the maximum sum ending at a
        # specific index becomes less than 0,
        # then making it equal to 0.
        if (max_ending_here < 0):
            max_ending_here = 0
    return max_so_far
 
# Function to find the minimum possible sum
# of the array elements after performing
# the given operation
def minPossibleSum(a,n, x):
    mxSum = maxSubArraySum(a, n)
    sum = 0
 
    # Finding the sum of the array
    for i in range(n):
        sum += a[i]
 
    # Computing the minimum sum of the array
    sum = sum - mxSum + mxSum / x
    print(round(sum,2))
 
# Driver code
if __name__ == '__main__':
    N = 3
    X = 2
    A=[1, -2, 3]
    minPossibleSum(A, N, X)
 
# This code is contributed by mohit kumar 29
 
 

C#




// C# program to find the minimum possible sum
// of the array elements after performing
// the given operation
using System;
 
class GFG{
   
// Function to find the maximum sum
// of the sub array
static double maxSubArraySum(double[] a, int size)
{
   
    // max_so_far represents the maximum sum
    // found till now and max_ending_here
    // represents the maximum sum ending at
    // a specific index
    double max_so_far = Int32.MinValue,
           max_ending_here = 0;
   
    // Iterating through the array to find
    // the maximum sum of the subarray
    for (int i = 0; i < size; i++) {
        max_ending_here = max_ending_here + a[i];
        if (max_so_far < max_ending_here)
            max_so_far = max_ending_here;
   
        // If the maximum sum ending at a
        // specific index becomes less than 0,
        // then making it equal to 0.
        if (max_ending_here < 0)
            max_ending_here = 0;
    }
    return max_so_far;
}
   
// Function to find the minimum possible sum
// of the array elements after performing
// the given operation
static void minPossibleSum(double[] a, int n, double x)
{
    double mxSum = maxSubArraySum(a, n);
    double sum = 0;
   
    // Finding the sum of the array
    for (int i = 0; i < n; i++) {
        sum += a[i];
    }
   
    // Computing the minimum sum of the array
    sum = sum - mxSum + mxSum / x;
   
    Console.Write(sum +"\n");
}
   
// Driver code
public static void Main()
{
    int N = 3;
    double X = 2;
    double[] A = { 1, -2, 3 };
    minPossibleSum(A, N, X);
}
}
 
// This code is contributed by chitranayal
 
 

Javascript




<script>
 
// Javascript program to find the minimum possible sum
// of the array elements after performing
// the given operation
 
// Function to find the maximum sum
// of the sub array
function maxSubArraySum( a, size)
{
 
    // max_so_far represents the maximum sum
    // found till now and max_ending_here
    // represents the maximum sum ending at
    // a specific index
    var max_so_far = -1000000000,
           max_ending_here = 0;
 
    // Iterating through the array to find
    // the maximum sum of the subarray
    for (var i = 0; i < size; i++) {
        max_ending_here = max_ending_here + a[i];
        if (max_so_far < max_ending_here)
            max_so_far = max_ending_here;
 
        // If the maximum sum ending at a
        // specific index becomes less than 0,
        // then making it equal to 0.
        if (max_ending_here < 0)
            max_ending_here = 0;
    }
    return max_so_far;
}
 
// Function to find the minimum possible sum
// of the array elements after performing
// the given operation
function minPossibleSum(a, n, x)
{
    var mxSum = maxSubArraySum(a, n);
    var sum = 0;
 
    // Finding the sum of the array
    for (var i = 0; i < n; i++) {
        sum += a[i];
    }
 
    // Computing the minimum sum of the array
    sum = sum - mxSum + mxSum / x;
 
    document.write(sum);
}
 
// Driver code
var N = 3;
var X = 2;
var A = [ 1, -2, 3 ];
minPossibleSum(A, N, X);
 
// This code is contributed by rutvik_56.
</script>
 
 
Output: 
0.5

 

Time Complexity: O(N), as we are using a loop to traverse N times so it will cost us O(N) time.
Auxiliary Space: O(1), as we are not using any extra space.
 



Next Article
Maximise minimum element possible in Array after performing given operations
author
spp____
Improve
Article Tags :
  • Arrays
  • DSA
  • Mathematical
  • Kadane
  • subarray
Practice Tags :
  • Arrays
  • Kadane
  • Mathematical

Similar Reads

  • Maximise minimum element possible in Array after performing given operations
    Given an array arr[] of size N. The task is to maximize the minimum value of the array after performing given operations. In an operation, value x can be chosen and A value 3 * x can be subtracted from the arr[i] element.A value x is added to arr[i-1]. andA value of 2 * x can be added to arr[i-2]. F
    11 min read
  • Minimum sum of Quotients after performing the given operation
    Given an array A[] of length N, we can change the value of exactly one element of the array to any integer greater than 0, such that the sum of quotients of all the elements when divided by the new element is minimum. In other words, we have to find: [Tex]min(\Sigma(A[i]/A[k])) [/Tex], where 0 <=
    9 min read
  • Maximum score possible after performing given operations on an Array
    Given an array A of size N, the task is to find the maximum score possible of this array. The score of an array is calculated by performing the following operations on the array N times: If the operation is odd-numbered, the score is incremented by the sum of all elements of the current array. If th
    15+ 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 sum of array elements removed by performing the given operations
    Given two arrays arr[] and min[] consisting of N integers and an integer K. For each index i, arr[i] can be reduced to at most min[i]. Consider a variable, say S(initially 0). The task is to find the maximum value of S that can be obtained by performing the following operations: Choose an index i an
    8 min read
  • Make the array elements equal by performing given operations minimum number of times
    Given an array arr[] of size N, the task is to make all the array elements equal by performing following operations minimum number of times: Increase all array elements of any suffix array by 1.Decrease all the elements of any suffix array by 1.Replace any array element y another. Examples: Input: a
    7 min read
  • Sum of the updated array after performing the given operation
    Given an array arr[] of N elements, the task is to update all the array elements such that an element arr[i] is updated as arr[i] = arr[i] - X where X = arr[i + 1] + arr[i + 2] + ... + arr[N - 1] and finally print the sum of the updated array.Examples: Input: arr[] = {40, 25, 12, 10} Output: 8 The u
    8 min read
  • Minimum sum of product of elements of pairs of the given array
    Given an array arr[] of even number of element N in it. The task is to form N/2 pairs such that sum of product of elements in those pairs is minimum. Examples Input: arr[] = { 1, 6, 3, 1, 7, 8 } Output: 270 Explanation: The pair formed are {1, 1}, {3, 6}, {7, 8} Product of sum of these pairs = 2 * 9
    5 min read
  • Find the sum of array after performing every query
    Given an array arr[] of size N and Q queries where every query contains two integers X and Y, the task is to find the sum of an array after performing each Q queries such that for every query, the element in the array arr[] with value X is updated to Y. Find the sum of the array after every query. E
    7 min read
  • Minimum operations of given type required to empty given array
    Given an array arr[] of size N, the task is to find the total count of operations required to remove all the array elements such that if the first element of the array is the smallest element, then remove that element, otherwise move the first element to the end of the array. Examples: Input: A[] =
    14 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