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 Problems on DP
  • Practice DP
  • MCQs on DP
  • Tutorial on Dynamic Programming
  • Optimal Substructure
  • Overlapping Subproblem
  • Memoization
  • Tabulation
  • Tabulation vs Memoization
  • 0/1 Knapsack
  • Unbounded Knapsack
  • Subset Sum
  • LCS
  • LIS
  • Coin Change
  • Word Break
  • Egg Dropping Puzzle
  • Matrix Chain Multiplication
  • Palindrome Partitioning
  • DP on Arrays
  • DP with Bitmasking
  • Digit DP
  • DP on Trees
  • DP on Graph
Open In App
Next Article:
Maximum subsequence sum with adjacent elements having atleast K difference in index
Next article icon

Partitioning into two contiguous element subarrays with equal sums

Last Updated : 17 Aug, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array of n positive integers. Find a minimum positive element to be added to one of the indexes in the array such that it can be partitioned into two contiguous sub-arrays of equal sums. Output the minimum element to be added and the position where it is to be added. If multiple positions are possible then return the least one.

Examples:  

Input : arr[] = { 10, 1, 2, 3, 4 } 
Output : 0 0 
Explanation: The array can already be partitioned into two contiguous subarrays i.e. {10} and {1, 2, 3, 4} with equal sums. So we need to add 0 at any position. (least position is 0) 
  
Input : arr[] = { 5, 4 } 
Output : 1 1 
Explanation: We need to add 1 to 4 so that two sub arrays are {5},{5} hence output is 1 1 (minimum element and it's position where it is to be added.

Prerequisites: Prefix Sums

Method 1 (Simple): A naive approach is to calculate the sum of elements from (arr[0] to arr[i]) and (arr[i+1] to arr[n-1]), and at each step find the difference between these two sums, minimum difference will give the element to be added.

Method 2 (Efficient): Careful analysis suggests that we can use the concept of prefix sums and suffix sums. Calculate both of them and find the absolute difference between prefixSum[i] (where prefixSum[i] is the sum of array elements upto ith position) and suffixSum[i + 1] (where suffixSum[i + 1] is the sum of array elements from (i + 1)th position to last position). 

For e.g.  

arr              10    1    2    3    4 prefixSum        10    11   13   16   20 suffixSum        20    10   9    7    4  Absolute difference between suffixSum[i + 1] and prefixSum[i] 10 - 10 = 0 // minimum 11 - 9  = 1 13 - 7  = 6 16 - 4  = 12 Thus, minimum element is 0, for position, if prefixSum[i] is greater than suffixSum[i + 1], then position is "i + 1". else it's is "i".

Below is the implementation of above approach. 

C++
// CPP Program to find the minimum element to  // be added such that the array can be partitioned  // into two contiguous subarrays with equal sums #include <bits/stdc++.h>  using namespace std;  // Structure to store the minimum element // and its position  struct data {     int element;     int position; };  struct data findMinElement(int arr[], int n) {     struct data result;           // initialize prefix and suffix sum arrays with 0     int prefixSum[n] = { 0 };      int suffixSum[n] = { 0 };      prefixSum[0] = arr[0];     for (int i = 1; i < n; i++) {         // add current element to Sum         prefixSum[i] = prefixSum[i - 1] + arr[i];     }      suffixSum[n - 1] = arr[n - 1];     for (int i = n - 2; i >= 0; i--) {         // add current element to Sum         suffixSum[i] = suffixSum[i + 1] + arr[i];     }          // initialize the minimum element to be a large value     int min = suffixSum[0];      int pos;      for (int i = 0; i < n - 1; i++) {         // check for the minimum absolute difference          // between current prefix sum and the next          // suffix sum element         if (abs(suffixSum[i + 1] - prefixSum[i]) < min) {             min = abs(suffixSum[i + 1] - prefixSum[i]);              // if prefixsum has a greater value then position              // is the next element, else it's the same element.             if (suffixSum[i + 1] < prefixSum[i]) pos = i + 1;             else     pos = i;         }     }      // return the data in struct.     result.element = min;     result.position = pos;     return result; }  // Driver Code  int main() {     int arr[] = { 10, 1, 2, 3, 4 };     int n = sizeof(arr) / sizeof(arr[0]);     struct data values;      values = findMinElement(arr, n);     cout << "Minimum element : " << values.element          << endl << "Position : " << values.position;     return 0; } 
Java
// Java Program to find the minimum element to  // be added such that the array can be partitioned  // into two contiguous subarrays with equal sums import java.util.*;  class GFG {      // Structure to store the minimum element // and its position  static class data  {     int element;     int position; };  static data findMinElement(int arr[], int n) {     data result=new data();           // initialize prefix and suffix sum arrays with 0     int []prefixSum = new int[n];      int []suffixSum = new int[n];      prefixSum[0] = arr[0];     for (int i = 1; i < n; i++)     {         // add current element to Sum         prefixSum[i] = prefixSum[i - 1] + arr[i];     }      suffixSum[n - 1] = arr[n - 1];     for (int i = n - 2; i >= 0; i--)     {         // add current element to Sum         suffixSum[i] = suffixSum[i + 1] + arr[i];     }          // initialize the minimum element to be a large value     int min = suffixSum[0];      int pos=0;      for (int i = 0; i < n - 1; i++)      {         // check for the minimum absolute difference          // between current prefix sum and the next          // suffix sum element         if (Math.abs(suffixSum[i + 1] - prefixSum[i]) < min)          {             min = Math.abs(suffixSum[i + 1] - prefixSum[i]);              // if prefixsum has a greater value then position              // is the next element, else it's the same element.             if (suffixSum[i + 1] < prefixSum[i]) pos = i + 1;             else     pos = i;         }     }      // return the data in struct.     result.element = min;     result.position = pos;     return result; }  // Driver Code  public static void main(String[] args) {     int arr[] = { 10, 1, 2, 3, 4 };     int n = arr.length;     data values;      values = findMinElement(arr, n);     System.out.println("Minimum element : " + values.element          + "\nPosition : " + values.position); } }  // This code is contributed by Rajput-Ji 
Python3
# Python Program to find the minimum element to # be added such that the array can be partitioned # into two contiguous subarrays with equal sums  # Class to store the minimum element # and its position class Data:     def __init__(self):         self.element = -1         self.position = -1   def findMinElement(arr, n):     result = Data()      # initialize prefix and suffix sum arrays with 0     prefixSum = [0]*n     suffixSum = [0]*n      prefixSum[0] = arr[0]     for i in range(1, n):          # add current element to Sum         prefixSum[i] = prefixSum[i-1] + arr[i]\      suffixSum[n-1] = arr[n-1]     for i in range(n-2, -1, -1):          # add current element to Sum         suffixSum[i] = suffixSum[i+1] + arr[i]      # initialize the minimum element to be a large value     mini = suffixSum[0]     pos = 0     for i in range(n-1):          # check for the minimum absolute difference         # between current prefix sum and the next         # suffix sum element         if abs(suffixSum[i+1]-prefixSum[i]) < mini:             mini = abs(suffixSum[i+1] - prefixSum[i])              # if prefixsum has a greater value then position             # is the next element, else it's the same element.             if suffixSum[i+1] < prefixSum[i]:                 pos = i+1             else:                 pos = i      # return the data in class.     result.element = mini     result.position = pos      return result   # Driver Code if __name__ == "__main__":     arr = [10, 1, 2, 3, 4]     n = len(arr)     values = Data()      values = findMinElement(arr, n)      print("Minimum element :", values.element, "\nPosition :", values.position)  # This code is contributed by # sanjeev2552 
C#
// C# Program to find the minimum element  // to be added such that the array can be  // partitioned into two contiguous subarrays // with equal sums using System;  class GFG {      // Structure to store the minimum element // and its position  public class data  {     public int element;     public int position; };  static data findMinElement(int []arr, int n) {     data result = new data();           // initialize prefix and suffix     // sum arrays with 0     int []prefixSum = new int[n];      int []suffixSum = new int[n];      prefixSum[0] = arr[0];     for (int i = 1; i < n; i++)     {         // add current element to Sum         prefixSum[i] = prefixSum[i - 1] + arr[i];     }      suffixSum[n - 1] = arr[n - 1];     for (int i = n - 2; i >= 0; i--)     {         // add current element to Sum         suffixSum[i] = suffixSum[i + 1] + arr[i];     }          // initialize the minimum element     // to be a large value     int min = suffixSum[0];      int pos = 0;      for (int i = 0; i < n - 1; i++)      {         // check for the minimum absolute difference          // between current prefix sum and the next          // suffix sum element         if (Math.Abs(suffixSum[i + 1] -                       prefixSum[i]) < min)          {             min = Math.Abs(suffixSum[i + 1] -                            prefixSum[i]);              // if prefixsum has a greater value then position              // is the next element, else it's the same element.             if (suffixSum[i + 1] < prefixSum[i])                  pos = i + 1;             else                      pos = i;         }     }      // return the data in struct.     result.element = min;     result.position = pos;     return result; }  // Driver Code  public static void Main(String[] args) {     int []arr = { 10, 1, 2, 3, 4 };     int n = arr.Length;     data values;      values = findMinElement(arr, n);     Console.WriteLine("Minimum element : " +                              values.element +                             "\nPosition : " +                             values.position); } }  // This code is contributed by PrinciRaj1992  
JavaScript
<script>  // JavaScript Program to find the minimum element to // be added such that the array can be partitioned // into two contiguous subarrays with equal sums   // Structure to store the minimum element // and its position class data {     constructor(element, position){         this.element = element;         this.position = position;     } };  function findMinElement(arr, n) {     let result = new data();          // initialize prefix and suffix sum arrays with 0     let prefixSum = new Array(n);     let suffixSum = new Array(n);      prefixSum[0] = arr[0];     for (let i = 1; i < n; i++)     {         // add current element to Sum         prefixSum[i] = prefixSum[i - 1] + arr[i];     }      suffixSum[n - 1] = arr[n - 1];     for (let i = n - 2; i >= 0; i--)     {         // add current element to Sum         suffixSum[i] = suffixSum[i + 1] + arr[i];     }          // initialize the minimum element to be a large value     let min = suffixSum[0];     let pos=0;      for (let i = 0; i < n - 1; i++)     {         // check for the minimum absolute difference         // between current prefix sum and the next         // suffix sum element         if (Math.abs(suffixSum[i + 1] - prefixSum[i]) < min)         {             min = Math.abs(suffixSum[i + 1] - prefixSum[i]);              // if prefixsum has a greater value then position             // is the next element, else it's the same element.             if (suffixSum[i + 1] < prefixSum[i]) pos = i + 1;             else     pos = i;         }     }      // return the data in struct.     result.element = min;     result.position = pos;     return result; }  // Driver Code      let arr = [ 10, 1, 2, 3, 4 ];     let n = arr.length;     let values;      values = findMinElement(arr, n);     document.write("Minimum element : " +      values.element + "<br>Position : " + values.position);  // This code is contributed by _saurabh_jaiswal  </script> 

Output
Minimum element : 0 Position : 0

Complexity Analysis:

  • Time Complexity: O(n)
  • Auxiliary Space: O(n)

Next Article
Maximum subsequence sum with adjacent elements having atleast K difference in index

S

shubham bhuyan
Improve
Article Tags :
  • Dynamic Programming
  • C++ Programs
  • DSA
Practice Tags :
  • Dynamic Programming

Similar Reads

  • Count of contiguous subarrays possible for every index by including the element at that index
    Given a number N which represents the size of the array A[], the task is to find the number of contiguous subarrays that can be formed for every index of the array by including the element at that index in the original array. Examples: Input: N = 4 Output: {4, 6, 6, 4} Explanation: Since the size of
    8 min read
  • Split the array into equal sum parts according to given conditions
    Given an integer array arr[], the task is to check if the input array can be split in two sub-arrays such that: Sum of both the sub-arrays is equal.All the elements which are divisible by 5 should be in the same group.All the elements which are divisible by 3 (but not divisible by 5) should be in th
    8 min read
  • Longest unique subarray of an Array with maximum sum in another Array
    Given two arrays X[] and Y[] of size N, the task is to find the longest subarray in X[] containing only unique values such that a subarray with similar indices in Y[] should have a maximum sum. The value of array elements is in the range [0, 1000]. Examples: Input: N = 5, X[] = {0, 1, 2, 0, 2}, Y[]
    10 min read
  • Count ways to split array into two subsets having difference between their sum equal to K
    Given an array A[] of size N and an integer diff, the task is to count the number of ways to split the array into two subsets (non-empty subset is possible) such that the difference between their sums is equal to diff. Examples: Input: A[] = {1, 1, 2, 3}, diff = 1 Output: 3 Explanation: All possible
    14 min read
  • Maximum subsequence sum with adjacent elements having atleast K difference in index
    Given an array arr[] consisting of integers of length N and an integer K (1 ? k ? N), the task is to find the maximum subsequence sum in the array such that adjacent elements in that subsequence have at least a difference of K in their indices in the original array. Examples: Input: arr[] = {1, 2, -
    8 min read
  • Split squares of first N natural numbers into two sets with minimum absolute difference of their sums
    Given an integer N, the task is to partition the squares of first N( always a multiple of 8 ) natural numbers into two sets such that the difference of their subset sums is minimized. Print both the subsets as the required answer. Examples: Input: N = 8Output:01 16 36 494 9 25 64Explanation: Squares
    9 min read
  • Minimize insertions in an array to obtain all sums upto N
    Given a sorted array arr[] of positive integers of size K, and an integer N. The task is to find the minimum number of elements to be inserted in this array, such that all positive integers in range [1, N] can be obtained as a sum of subsets of the modified array. Note: The array won't have any dupl
    10 min read
  • Find maximum Subsequence Sum according to given conditions
    Given an integer array nums and an integer K, The task is to find the maximum sum of a non-empty subsequence of the array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= K is satisfied. A subsequence of an array is obtai
    5 min read
  • Maximum Sum SubArray using Divide and Conquer | Set 2
    Given an array arr[] of integers, the task is to find the maximum sum sub-array among all the possible sub-arrays.Examples: Input: arr[] = {-2, 1, -3, 4, -1, 2, 1, -5, 4} Output: 6 {4, -1, 2, 1} is the required sub-array.Input: arr[] = {2, 2, -2} Output: 4 Approach: Till now we are only aware of Kad
    13 min read
  • Minimum possible value T such that at most D Partitions of the Array having at most sum T is possible
    Given an array arr[] consisting of N integers and an integer D, the task is to find the least integer T such that the entire array can be partitioned into at most D subarrays from the given array with sum atmost T. Examples: Input: D = 5, arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} Output: 15 Explanatio
    9 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