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:
Cost of rearranging the array such that no element exceeds the sum of its adjacent elements
Next article icon

Maximum sum of Array formed by replacing each element with sum of adjacent elements

Last Updated : 06 Jun, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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 elements: 
4 + 2 = 6 
6 + 1 = 7 
7 + 3 = 10 
Array formed by replacing each element of the original array with the sum of adjacent elements: [6, 7, 10] 
Therefore, Sum = 6 + 7 + 10 = 23
Input: arr = [2, 3, 9, 8, 4] 
Output: 88 
Explanation: 
Replacing each element of the original array with the sum of adjacent elements to get maximum sum: 
9 + 8 = 17 
17 + 4 = 21 
21 + 3 = 24 
24 + 2 = 26 
Array formed by replacing each element of the original array with the sum of adjacent elements: [17, 21, 24, 26] 
Therefore, Sum = 17 + 21 + 24 + 26 = 88. 
 

 

Approach: 
 

  • Scan through the array to pick the adjacent pair with the highest sum.
  • From there on, using Greedy algorithm, pick the left or right integer, whichever is greater.
  • Repeat the process till only a single element is left in the array.

Below is the implementation of the above approach: 
 

C++




// C++ program to find the maximum sum
// of Array formed by replacing each
// element with sum of adjacent elements
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to calculate the possible
// maximum cost of the array
int getTotalTime(vector<int>& arr)
{
 
    // Check if array size is 0
    if (arr.size() == 0)
        return 0;
 
    // Initialise left and right variables
    int l = -1, r = -1;
 
    for (int i = 1; i < arr.size(); i++) {
        if (l == -1
            || (arr[i - 1] + arr[i])
                   > (arr[l] + arr[r])) {
            l = i - 1;
            r = i;
        }
    }
 
    // Calculate the current cost
    int currCost = arr[l] + arr[r];
 
    int totalCost = currCost;
 
    l--;
    r++;
 
    // Iterate until left variable reaches 0
    // and right variable is less than array size
    while (l >= 0 || r < arr.size()) {
 
        int left = l < 0
                       ? INT_MIN
                       : arr[l];
        int right = r >= arr.size()
                        ? INT_MIN
                        : arr[r];
 
        // Check if left integer is greater
        // than the right then add left integer
        // to the current cost and
        // decrement the left variable
        if (left > right) {
            currCost += left;
 
            totalCost += currCost;
 
            l--;
        }
 
        // Executes if right integer is
        // greater than left then add
        // right integer to the current cost
        // and increment the right variable
        else {
 
            currCost += right;
            totalCost += currCost;
            r++;
        }
    }
 
    // Return the final answer
    return totalCost;
}
 
// Driver code
int main(int argc, char* argv[])
{
    vector<int> arr = { 2, 3, 9, 8, 4 };
 
    cout << getTotalTime(arr) << endl;
 
    return 0;
}
 
 

Java




// Java program to find the maximum sum
// of array formed by replacing each
// element with sum of adjacent elements
class GFG{
 
// Function to calculate the possible
// maximum cost of the array
static int getTotalTime(int []arr)
{
     
    // Check if array size is 0
    if (arr.length == 0)
        return 0;
 
    // Initialise left and right variables
    int l = -1, r = -1;
 
    for(int i = 1; i < arr.length; i++)
    {
       if (l == -1 || (arr[i - 1] + arr[i]) >
                          (arr[l] + arr[r]))
       {
           l = i - 1;
           r = i;
       }
    }
 
    // Calculate the current cost
    int currCost = arr[l] + arr[r];
 
    int totalCost = currCost;
 
    l--;
    r++;
 
    // Iterate until left variable reaches 0
    // and right variable is less than array size
    while (l >= 0 || r < arr.length)
    {
        int left = (l < 0 ?
                    Integer.MIN_VALUE : arr[l]);
        int right = (r >= arr.length ?
                    Integer.MIN_VALUE : arr[r]);
 
        // Check if left integer is greater
        // than the right then add left integer
        // to the current cost and
        // decrement the left variable
        if (left > right)
        {
            currCost += left;
            totalCost += currCost;
            l--;
        }
 
        // Executes if right integer is
        // greater than left then add
        // right integer to the current cost
        // and increment the right variable
        else
        {
            currCost += right;
            totalCost += currCost;
            r++;
        }
    }
 
    // Return the final answer
    return totalCost;
}
 
// Driver code
public static void main(String[] args)
{
    int []arr = { 2, 3, 9, 8, 4 };
 
    System.out.print(getTotalTime(arr) + "\n");
}
}
 
// This code is contributed by PrinciRaj1992
 
 

Python3




# Python3 program to find the maximum sum
# of Array formed by replacing each
# element with sum of adjacent elements
import sys
 
# Function to calculate the possible
# maximum cost of the array
def getTotalTime(arr):
     
    # Check if array size is 0
    if (len(arr) == 0):
        return 0
 
    # Initialise left and right variables
    l = -1
    r = -1
 
    for i in range(1, len(arr), 1):
        if (l == -1 or (arr[i - 1] + arr[i]) > (arr[l] + arr[r])):
            l = i - 1
            r = i
 
    # Calculate the current cost
    currCost = arr[l] + arr[r]
 
    totalCost = currCost
 
    l -= 1
    r += 1
 
    # Iterate until left variable reaches 0
    # and right variable is less than array size
    while (l >= 0 or r < len(arr)):
        if(l < 0):
            left = sys.maxsize
        else:
            left = arr[l]
        if (r >= len(arr)):
            right = -sys.maxsize - 1
        else:
            right = arr[r]
 
        # Check if left integer is greater
        # than the right then add left integer
        # to the current cost and
        # decrement the left variable
        if (left > right):
            currCost += left
 
            totalCost += currCost
 
            l -= 1
 
        # Executes if right integer is
        # greater than left then add
        # right integer to the current cost
        # and increment the right variable
        else:
            currCost += right
            totalCost += currCost
            r += 1
 
    # Return the final answer
    return totalCost
 
# Driver code
if __name__ == '__main__':
    arr = [2, 3, 9, 8, 4]
 
    print(getTotalTime(arr))
 
# This code is contributed by Surendra_Gangwar
 
 

C#




// C# program to find the maximum sum
// of array formed by replacing each
// element with sum of adjacent elements
using System;
 
class GFG{
  
// Function to calculate the possible
// maximum cost of the array
static int getTotalTime(int []arr)
{
      
    // Check if array size is 0
    if (arr.Length == 0)
        return 0;
  
    // Initialise left and right variables
    int l = -1, r = -1;
  
    for(int i = 1; i < arr.Length; i++)
    {
       if (l == -1 || (arr[i - 1] + arr[i]) >
                          (arr[l] + arr[r]))
       {
           l = i - 1;
           r = i;
       }
    }
  
    // Calculate the current cost
    int currCost = arr[l] + arr[r];
  
    int totalCost = currCost;
  
    l--;
    r++;
  
    // Iterate until left variable reaches 0
    // and right variable is less than array size
    while (l >= 0 || r < arr.Length)
    {
        int left = (l < 0 ?
                    int.MinValue : arr[l]);
        int right = (r >= arr.Length ?
                    int.MinValue : arr[r]);
  
        // Check if left integer is greater
        // than the right then add left integer
        // to the current cost and
        // decrement the left variable
        if (left > right)
        {
            currCost += left;
            totalCost += currCost;
            l--;
        }
  
        // Executes if right integer is
        // greater than left then add
        // right integer to the current cost
        // and increment the right variable
        else
        {
            currCost += right;
            totalCost += currCost;
            r++;
        }
    }
  
    // Return the readonly answer
    return totalCost;
}
  
// Driver code
public static void Main(String[] args)
{
    int []arr = { 2, 3, 9, 8, 4 };
  
    Console.Write(getTotalTime(arr) + "\n");
}
}
 
// This code is contributed by PrinciRaj1992
 
 

Javascript




<script>
 
// Javascript program to find the maximum sum
// of Array formed by replacing each
// element with sum of adjacent elements
 
// Function to calculate the possible
// maximum cost of the array
function getTotalTime(arr)
{
 
    // Check if array size is 0
    if (arr.length == 0)
        return 0;
 
    // Initialise left and right variables
    var l = -1, r = -1;
 
    for (var i = 1; i < arr.length; i++) {
        if (l == -1
            || (arr[i - 1] + arr[i])
                   > (arr[l] + arr[r])) {
            l = i - 1;
            r = i;
        }
    }
 
    // Calculate the current cost
    var currCost = arr[l] + arr[r];
 
    var totalCost = currCost;
 
    l--;
    r++;
 
    // Iterate until left variable reaches 0
    // and right variable is less than array size
    while (l >= 0 || r < arr.length) {
 
        var left = l < 0
                       ? -1000000000
                       : arr[l];
        var right = r >= arr.length
                        ? -1000000000
                        : arr[r];
 
        // Check if left integer is greater
        // than the right then add left integer
        // to the current cost and
        // decrement the left variable
        if (left > right) {
            currCost += left;
 
            totalCost += currCost;
 
            l--;
        }
 
        // Executes if right integer is
        // greater than left then add
        // right integer to the current cost
        // and increment the right variable
        else {
 
            currCost += right;
            totalCost += currCost;
            r++;
        }
    }
 
    // Return the final answer
    return totalCost;
}
 
// Driver code
var arr = [2, 3, 9, 8, 4];
document.write( getTotalTime(arr));
 
// This code is contributed by noob2000.
</script>
 
 
Output: 
88

 

Time Complexity: O(N), as we are using a loop to traverse N times.

Auxiliary Space: O(1), as we are not using any extra space.
 



Next Article
Cost of rearranging the array such that no element exceeds the sum of its adjacent elements
author
coder001
Improve
Article Tags :
  • Arrays
  • DSA
Practice Tags :
  • Arrays

Similar Reads

  • Minimize sum of Array formed using given relation between adjacent elements
    Given a binary string S of length N, consisting of 0's and 1's, the task is to find the minimum sum of the array of non-negative integers of length N+1 created by following the below conditions: If the ith number in the given binary string is 0, then the (i + 1)th number in the array must be less th
    11 min read
  • Maximize the sum of Array by formed by adding pair of elements
    Given an array a[] of 2*N integers, The task is to make the array a[] of size N i.e, reducing it to half size such that, a[i] = ?(a[j] + a[k]) / N?, 0 < j, k < 2*N - 1. and form the array so that the sum of all the elements of the array a[], will be maximum. Output the maximum sum. Examples: I
    6 min read
  • Minimize Array sum by replacing elements such that Relation among adjacent elements in maintained
    Given an array arr[] of size N, the task is to minimize the array sum after replacing array elements with positive integers in a way such the relation among the adjacent elements (pattern of the array)is maintained. Note: If arr[i] = arr[i+1] then in the new array they both can be the same or one ca
    7 min read
  • Maximize the count of adjacent element pairs with even sum by rearranging the Array
    Given an array, arr[] of N integers, the task is to find the maximum possible count of adjacent pairs with an even sum, rearranging the array arr[]. Examples: Input: arr[] = {5, 5, 1}Output: 2Explanation:The given array is already arranged to give the maximum count of adjacent pairs with an even sum
    6 min read
  • Cost of rearranging the array such that no element exceeds the sum of its adjacent elements
    Given an array arr[] of N unique integers, the task is to find the cost to arrange them in a circular arrangement in such a way that every element is less than or equal to the sum of its adjacent elements. Cost of moving an element from index i in original array to index j in final arrangement is |i
    8 min read
  • Rearrange given Array by replacing every element with the element located at mean of adjacent elements
    Given an array arr[]. The array contains numbers from 0 to N-1 only, where N is the size of arr[]. The task is to modify the array in such that for each i from 0≤i<N, arr[i] = arr[ (arr[i-1] + arr[i+1]) / 2 ] There are a few exceptions: For first element of the array, arr[i-1] = 0; because previo
    9 min read
  • Make all array elements equal by replacing adjacent pairs by their sum
    Given an array arr[] consisting of N integers, the task is to replace a minimum number of pairs of adjacent elements by their sum to make all array elements equal. Print the minimum number of such operations required. Examples: Input: arr[] = {1, 2, 3}Output: 1Explanation: Replace arr[0] and arr[1]
    8 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
  • Minimize sum of adjacent difference with removal of one element from array
    Given an array of positive integers of size greater than 2. The task is to find the minimum value of the sum of consecutive difference modulus of an array, i.e. the value of |A1-A0|+|A2-A1|+|A3-A2|+......+|An-1-An-2|+|An-A(n-1)| after removal of one element from the array, where An represents the nt
    8 min read
  • Maximum subarray sum with same first and last element formed by removing elements
    Given an array arr[] of N integers, the task is to find the maximum sum of subarray having length an at least 2 whose first and last elements are the same after removing any number of array elements. If there exists no such array, then print 0. Examples: Input: arr[] = {-1, -3, -2, 4, -1, 3}Output:
    6 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