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
  • Algorithms
  • Analysis of Algorithms
  • Sorting
  • Searching
  • Greedy
  • Recursion
  • Backtracking
  • Dynamic Programming
  • Divide and Conquer
  • Geometric Algorithms
  • Mathematical Algorithms
  • Pattern Searching
  • Bitwise Algorithms
  • Branch & Bound
  • Randomized Algorithms
Open In App
Next Article:
Maximum sum subarray of size K with sum less than X
Next article icon

Minimize the maximum subarray sum with 1s and -2s

Last Updated : 05 Mar, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given two integers X and Y. X and Y represent the frequency of elements 1 and -2 you have. You have to arrange all elements such that the maximum sum over all subarrays is minimized, and then find the maximum subarray sum of such rearrangement.

Examples:

Input: X = 1, Y = 1
Output: 1
Explanation: X = 1 and Y = 1 means we have one 1 and one -2. There can be only two possible arrangements with these elements as {1, -2} or {-2, 1}. In both of the cases the maximum subarray sum will be 1.

Input: X = 5, Y = 1
Output: 3
Explanation: The optimal arrangement of elements will be {1, 1, -2, 1, 1, 1}. Then, the maximum subarray sum will be 3.

Approach: To solve the problem, follow the below idea:

  • In case the number of 1's are too great, the -2s won't affect the subarray sum too much. Hence, we also calculate the sum of the whole array, which is (X - 2*Y) (Since the whole array is also its own subarray).
  • If there are Y number of -2s then there will be (Y+1) groups of 1s in arrangement. For example, X = 5 and Y = 2, then the arrangement will be as follows: {}, -2, {}, -2, {}. Where "{}" shows the collective group of ones (equal to (Y+1) = 3). We need to distribute X number of 1s in (Y+1) spaces equally. So that the distribution will be as Ceil (X/ (Y+1)).
  • Then, the maximum subarray sum will be max of both of these as max((X - 2*Y), Ceil (X/ (Y+1))).
  • The problem is observation based. The main idea is, for any subarray to have its sum minimized, we need to distribute the 1s among the -2s such that the count of 1s in between -2s are smallest. This can only be done by optimally dividing the number of 1's between the 2's.

Illustration:

Let us understand it with some examples and find some observations:

  • Example 1: X = 5, Y = 2
    • We have five 1s and two -2s.
    • We need to distribute 1s in between -2s, then the optimal arrangement will be as follows: {1, 1, -2, 1, -2, 1, 1}. The maximum subarray sum will be 2 in this case. Max((X - 2*Y), Ciel (X/ (Y+1))) = 2.
  • Example 2: X = 5, Y = 1
    • We have five 1s and one -2s.
    • The optimal arrangement will be as follows: {1, 1, -2, 1, 1, 1}. The maximum subarray sum will be 3 in this case. Ceil(5/(1+1)) = 3. Max((X - 2*Y), Ciel (X/ (Y+1))) = 3.
  • Example 3: X = 1, Y = 3
    • We have one 1 and three -2s.
    • The optimal arrangement will be as follows: {-2, -2, -2, 1}. The maximum subarray sum will be 1. Max((X - 2*Y), Ciel (X/ (Y+1))) = 1.

Step-by-step algorithm:

  • Declare two variables let say A and B.
  • Initialize A with Ciel (X/ (Y+1)).
  • Initialize B with sum of all elements as (X - 2*Y).
  • Output Max (A, B).

Below is the implementation of the algorithm:

C++
#include <iostream> #include <cmath>  // Function to output the maximum subarray sum after // optimal arrangement void FindMaxSum(double X, double Y) {     double A = std::ceil(X / (Y + 1.0));     double B = (X - 2 * Y);     std::cout << std::max(A, B) << std::endl; }  // Driver Function int main() {     // Inputs     double X = 5, Y = 2;      // Function_call     FindMaxSum(X, Y);      return 0; }   // This code is contributed by akshitaguprzj3 
Java
// Java code to implement the approach  import java.util.*;  // Driver Class public class Main {      // Driver Function     public static void main(String[] args)     {         // Inputs         double X = 5, Y = 2;          // Function_call         FindMaxSum(X, Y);     }      // Function to output the maximum subarray sum after     // optimal arrangement     public static void FindMaxSum(Double X, Double Y)     {         double A = Math.ceil(X / (Y + 1.0));         double B = (X - 2 * Y);         System.out.println(Math.max(A, B));     } } 
Python3
# Python Implementation  import math  def find_max_sum(X, Y):     A = math.ceil(X / (Y + 1.0))     B = X - 2 * Y     return max(A, B)  X = 5 Y = 2  max_sum = find_max_sum(X, Y) print(max_sum)  # This code is contributed by Sakshi 
C#
// C# code to implement the approach using System;  // Driver Class public class GFG {     // Driver Function     public static void Main(string[] args)     {         // Inputs         double X = 5, Y = 2;          // Function_call         FindMaxSum(X, Y);     }      // Function to output the maximum subarray sum after     // optimal arrangement     public static void FindMaxSum(double X, double Y)     {         double A = Math.Ceiling(X / (Y + 1.0));         double B = (X - 2 * Y);         Console.WriteLine(Math.Max(A, B));     } } 
JavaScript
// Function to output the maximum subarray sum after optimal arrangement function findMaxSum(X, Y) {     let A = Math.ceil(X / (Y + 1));     let B = X - 2 * Y;     console.log(Math.max(A, B)); }  // Driver Function function main() {     // Inputs     let X = 5, Y = 2;      // Function call     findMaxSum(X, Y); }  // Invoke main function main(); 

Output
2.0

Time Complexity: O(1)
Auxiliary Space: O(1)


Next Article
Maximum sum subarray of size K with sum less than X

A

ayami
Improve
Article Tags :
  • Greedy
  • Geeks Premier League
  • DSA
  • Arrays
  • Geeks Premier League 2023
Practice Tags :
  • Arrays
  • Greedy

Similar Reads

  • Size of The Subarray With Maximum Sum
    Given an array arr[] of size N, the task is to find the length of the subarray having maximum sum. Examples : Input : a[] = {1, -2, 1, 1, -2, 1} Output : Length of the subarray is 2 Explanation : Subarray with consecutive elements and maximum sum will be {1, 1}. So length is 2 Input : ar[] = { -2, -
    10 min read
  • Print subarray with maximum sum
    Given an array arr[], the task is to print the subarray having maximum sum. Examples: Input: arr[] = {2, 3, -8, 7, -1, 2, 3}Output: 11Explanation: The subarray {7, -1, 2, 3} has the largest sum 11. Input: arr[] = {-2, -5, 6, -2, -3, 1, 5, -6}Output: {6, -2, -3, 1, 5}Explanation: The subarray {6, -2,
    13 min read
  • Maximum sum subarray of size K with sum less than X
    Given an array arr[] and two integers K and X, the task is to find the maximum sum among all subarrays of size K with the sum less than X. Examples: Input: arr[] = {20, 2, 3, 10, 5}, K = 3, X = 20Output: 18Explanation: Subarray of size 3 having maximum sum less than 20 is {3, 10, 5}. Therefore, requ
    7 min read
  • Minimum size Subarray with maximum sum in non-increasing order
    Given an array arr, the task is to find a subarray of the array elements whose sum is strictly greater than the rest of the elements. The size of the subarray should be minimum and the sum should be maximum and it must be in non-increasing order.Examples: Input: arr = [7, 6, 13, 12, 11] Output: 13 1
    6 min read
  • Javascript Program for Size of The Subarray With Maximum Sum
    An array is given, find length of the subarray having maximum sum. Examples : Input : a[] = {1, -2, 1, 1, -2, 1}Output : Length of the subarray is 2Explanation: Subarray with consecutive elements and maximum sum will be {1, 1}. So length is 2Input : ar[] = { -2, -3, 4, -1, -2, 1, 5, -3 }Output : Len
    2 min read
  • Minimizing Maximum Absolute Subarray Sums
    Given an array arr[] of size N, we can choose any real number X which when subtracted from all the elements of the array then the maximum absolute subarray sum among all the subarrays is minimum. The task is to return the minimum of maximum absolute sum among all the subarrays. Note: The answer shou
    12 min read
  • Length of the smallest subarray with maximum possible sum
    Given an array arr[] consisting of N non-negative integers, the task is to find the minimum length of the subarray whose sum is maximum. Example: Input: arr[] = {0, 2, 0, 0, 12, 0, 0, 0}Output: 4Explanation: The sum of the subarray {2, 0, 0, 12} = 2 + 0 + 0 + 12 = 14, which is maximum sum possible a
    6 min read
  • Split into K subarrays to minimize the maximum sum of all subarrays
    Given an array arr[] and a number k, split the given array into k subarrays such that the maximum subarray sum achievable out of k subarrays formed is the minimum possible. The task is to find that possible subarray sum. Examples: Input: arr[] = [1, 2, 3, 4], k = 3 Output: 4 Explanation: Optimal Spl
    11 min read
  • CSES Solutions - Maximum Subarray Sum
    Given an array arr[] of N integers, your task is to find the maximum sum of values in a contiguous, nonempty subarray. Examples: Input: N = 8, arr[] = {-1, 3, -2, 5, 3, -5, 2, 2}Output: 9Explanation: The subarray with maximum sum is {3, -2, 5, 3} with sum = 3 - 2 + 5 + 3 = 9. Input: N = 6, arr[] = {
    5 min read
  • CSES Solutions - Maximum Subarray Sum II
    Given an array arr[] of N integers, your task is to find the maximum sum of values in a contiguous subarray with length between A and B. Examples: Input: N = 8, A = 1, B = 2, arr[] = {-1, 3, -2, 5, 3, -5, 2, 2}Output: 8Explanation: The subarray with maximum sum is {5, 3}, the length between 1 and 2,
    12 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