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:
Maximize point to reduce Array by replacing Subarray with its sum
Next article icon

Maximize Array sum by replacing middle elements with min of Subarray corners

Last Updated : 04 Dec, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array A[] of length N. Then your task is to output the maximum sum that can be achieved by using the given operation at any number of times (possibly zero):

  • Select a subarray, whose length is at least 3.
  • Replace all the middle elements (Except the first and last) with a minimum of elements at both ends.

Examples:

Input: N = 3, A[] = {8, 1, 7}
Output: 22
Explanation: Let us take the subarray A[1, 3] = {8, 1, 7}. Middle element(s) are: {1}. Now minimum of A[1] and A[3] is = min(A[1], A[3]) = min(8, 7) = 7. Then, we replaced all the middle elements equal to min according to the operation. So, updated A[] = {8, 7, 7}. The sum of updated A[] = 22. Which is the maximum possible using a given operation. Therefore, output is 22.

Input: N = 2, A[] = {5, 2}
Output: 7
Explanation: No subarray of length at least 3 can be chosen, Thus can't apply any operation. So the maximum possible sum is 7.

Approach: Implement the idea below to solve the problem

The problem is based on the observations and can be solved using the Prefix and Suffix arrays. It must be noticed that for any index i, we can not make the element A[i] to be anything more than the minimum of the greatest element to its left and the greatest element to its right.

Steps were taken to solve the problem:

  • Create two arrays let say Prefix[] and Suffix[]
  • Set prefix[0] = A[0]
  • Run a loop for i = 1 to i < N and follow the below-mentioned steps under the scope of the loop
    • prefix[i] = max(prefix[i - 1], A[i])
  • Set suffix[N - 1] = A[N - 1]
  • Run a loop for i = N - 2 to I >=0 and follow the below-mentioned steps under the scope of the loop
    • suffix[i] = max(suffix[i + 1], A[i])
  • Create a variable let say Sum to store the max possible sum.
  • Run a loop for i = 1 to i < N - 1 and follow below mentioned steps under the scope of loop
    • Max1 = Prefix[i]
    • Max2 = Suffix[i]
    • sum += min(Max1, Max2)
  • Sum += A[0] + A[N - 1]
  • Output the value store in Sum.

Code to implement the approach:

C++
//code by FLutterfly #include <iostream> #include <algorithm>  using namespace std;  // Function prototype void Max_sum(int N, int A[]);  int main() {     // Input     int N = 2;     int A[] = {5, 2};      // Function call     Max_sum(N, A);      return 0; }  void Max_sum(int N, int A[]) {     // Prefix and Suffix Arrays     int prefix[N];     int suffix[N];      // Initializing prefix array     prefix[0] = A[0];     for (int i = 1; i < N; i++)     {         prefix[i] = max(prefix[i - 1], A[i]);     }      // Initializing suffix array     suffix[N - 1] = A[N - 1];     for (int i = N - 2; i >= 0; i--)     {         suffix[i] = max(suffix[i + 1], A[i]);     }      // Variable to store max sum     long long sum = 0;      // Calculating sum for all middle elements     for (int i = 1; i < N - 1; i++)     {         int maxi1 = prefix[i], maxi2 = suffix[i];         sum += min(maxi1, maxi2);     }      // Adding last elements of both ends into sum     sum += A[0] + A[N - 1];      // Printing the value of sum     cout << sum << endl; } 
Java
// Java code to implement the approach import java.util.*;  class Main {     public static void main(String[] args)     {         // Input         int N = 2;         int A[] = { 5, 2 };          // Function call         Max_sum(N, A);     }     public static void Max_sum(int N, int[] A)     {         // Prefix and Suffix Arrays         int[] prefix = new int[N];         int[] suffix = new int[N];          // Initializing prefix array         prefix[0] = A[0];         for (int i = 1; i < N; i++) {             prefix[i] = Math.max(prefix[i - 1], A[i]);         }          // Initializing suffix array         suffix[N - 1] = A[N - 1];         for (int i = N - 2; i >= 0; i--) {             suffix[i] = Math.max(suffix[i + 1], A[i]);         }          // Variable to store max sum         long sum = 0;          // Calculating sum for all middle elements         for (int i = 1; i < N - 1; i++) {             int maxi1 = prefix[i], maxi2 = suffix[i];             sum += Math.min(maxi1, maxi2);         }          // Adding last elements of both ends into sum         sum += A[0] + A[N - 1];          // Printing the value of sum         System.out.println(sum);     } } 
Python
# code by flutterfly def Max_sum(N, A):     # Prefix and Suffix Arrays     prefix = [0] * N     suffix = [0] * N      # Initializing prefix array     prefix[0] = A[0]     for i in range(1, N):         prefix[i] = max(prefix[i - 1], A[i])      # Initializing suffix array     suffix[N - 1] = A[N - 1]     for i in range(N - 2, -1, -1):         suffix[i] = max(suffix[i + 1], A[i])      # Variable to store max sum     sum_val = 0      # Calculating sum for all middle elements     for i in range(1, N - 1):         maxi1, maxi2 = prefix[i], suffix[i]         sum_val += min(maxi1, maxi2)      # Adding last elements of both ends into sum     sum_val += A[0] + A[N - 1]      # Printing the value of sum     print(sum_val)  # Input N = 2 A = [5, 2]  # Function call Max_sum(N, A) 
C#
//code by flutterfly using System;  class Program {     static void Main()     {         // Input         int N = 2;         int[] A = { 5, 2 };          // Function call         Max_sum(N, A);     }      static void Max_sum(int N, int[] A)     {         // Prefix and Suffix Arrays         int[] prefix = new int[N];         int[] suffix = new int[N];          // Initializing prefix array         prefix[0] = A[0];         for (int i = 1; i < N; i++)         {             prefix[i] = Math.Max(prefix[i - 1], A[i]);         }          // Initializing suffix array         suffix[N - 1] = A[N - 1];         for (int i = N - 2; i >= 0; i--)         {             suffix[i] = Math.Max(suffix[i + 1], A[i]);         }          // Variable to store max sum         long sum = 0;          // Calculating sum for all middle elements         for (int i = 1; i < N - 1; i++)         {             int maxi1 = prefix[i], maxi2 = suffix[i];             sum += Math.Min(maxi1, maxi2);         }          // Adding last elements of both ends into sum         sum += A[0] + A[N - 1];          // Printing the value of sum         Console.WriteLine(sum);     } } 
JavaScript
function Max_sum(N, A) {     // Prefix and Suffix Arrays     let prefix = new Array(N);     let suffix = new Array(N);      // Initializing prefix array     prefix[0] = A[0];     for (let i = 1; i < N; i++) {         prefix[i] = Math.max(prefix[i - 1], A[i]);     }      // Initializing suffix array     suffix[N - 1] = A[N - 1];     for (let i = N - 2; i >= 0; i--) {         suffix[i] = Math.max(suffix[i + 1], A[i]);     }      // Variable to store max sum     let sum = 0;      // Calculating sum for all middle elements     for (let i = 1; i < N - 1; i++) {         let maxi1 = prefix[i], maxi2 = suffix[i];         sum += Math.min(maxi1, maxi2);     }      // Adding last elements of both ends into sum     sum += A[0] + A[N - 1];      // Printing the value of sum     console.log(sum); }  // Input let N = 2; let A = [5, 2];  // Function call Max_sum(N, A); 

Output
7

Time Complexity: O(N)
Auxiliary Space: O(2*N), As Prefix and Suffix arrays of length N are used.


Next Article
Maximize point to reduce Array by replacing Subarray with its sum
author
pradeep6036ymca
Improve
Article Tags :
  • Geeks Premier League
  • DSA
  • Arrays
  • subarray
  • prefix
  • Geeks Premier League 2023
Practice Tags :
  • Arrays

Similar Reads

  • Maximize non decreasing Array size by replacing Subarray with sum
    Given an array arr[] of size N. In one operation only one subarray can be selected and replaced with the sum of the subarray. The task is to find the maximum size of the array after making it non-decreasing. Examples: Input: N = 5, arr[] = {5, 1, 6, 6, 6}Output: 4Explanation: maximum size non-decrea
    15+ min read
  • Maximize point to reduce Array by replacing Subarray with its sum
    Given an array arr[] of size, N, the task is to maximize the score to reduce the array to a single element by replacing any subarray with its sum where the score of one such operation is the product of subarray length and the minimum value of that subarray. Examples:Input: N = 2, arr[] = {1, 5}Outpu
    15 min read
  • Maximize the maximum subarray sum after removing atmost one element
    Given an array arr[] of N integers, the task is to find the maximum sum of a subarray with at most one deletion allowed. The size of subarray to be considered should be at least 1. Examples: Input: arr[] = {1, 2, 3, -2, 3} Output: 9 The maximum sub-array sum is given by the sub-array {2, 3, -2, 3} H
    2 min read
  • Rearrange array elements to maximize the sum of MEX of all prefix arrays
    Given an array arr[] of size N, the task is to rearrange the array elements such that the sum of MEX of all prefix arrays is the maximum possible. Note: MEX of a sequence is the minimum non-negative number not present in the sequence. Examples: Input: arr[] = {2, 0, 1}Output: 0, 1, 2Explanation:Sum
    7 min read
  • Maximize product of subarray sum with its minimum element
    Given an array arr[] consisting of N positive integers, the task is to find the maximum product of subarray sum with the minimum element of that subarray. Examples: Input: arr[] = {3, 1, 6, 4, 5, 2}Output: 60Explanation:The required maximum product can be obtained using subarray {6, 4, 5}Therefore,
    10 min read
  • Maximize product of subarray sum with its maximum element
    Given an array arr[] consisting of N positive integers, the task is to find the maximum product of the subarray sum with the maximum element of that subarray. Examples: Input: arr[] = {2, -3, 8, -2, 5}Output: 88Explanation:The required maximum product can be obtained using subarray {8, -2, 5}Therefo
    8 min read
  • Maximum sum of Array formed by replacing each element with sum of adjacent elements
    Given an array arr[] of size N, the task is to find the maximum sum of the Array formed by replacing each element of the original array with the sum of adjacent elements.Examples: Input: arr = [4, 2, 1, 3] Output: 23 Explanation: Replacing each element of the original array with the sum of adjacent
    9 min read
  • Maximize the sum of sum of the Array by removing end elements
    Given an array arr of size N, the task is to maximize the sum of sum, of the remaining elements in the array, by removing the end elements.Example: Input: arr[] = {2, 3} Output: 3 Explanation: At first we will delete 2, then sum of remaining elements = 3. Then delete 3. Therefore sum of sum = 3 + 0
    6 min read
  • Maximize the cost of reducing array elements
    Given an array arr[] of N positive integers. We can choose any one index(say K) of the array and reduce all the elements of the array from index 0 to K - 1 by 1. The cost of this operation is K. If at any index(say idx) element is reduced to 0 then we can't perform this operation in the range [idx,
    6 min read
  • Maximize the minimum array element by M subarray increments of size S
    Given an array arr[] of N integers and two integers S and M, the task is to maximize the minimum array element by incrementing any subarray of size S by 1, M number of times. Examples: Input: arr[] = {1, 2, 3, 4, 5, 6}, S = 2, M = 3Output: 3Explanation:Below are the operations performed:Operation 1:
    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