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 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 arrayint 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 codeint 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 elementsclass GFG{Â
// Function to calculate the possible// maximum cost of the arraystatic 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 codepublic 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 elementsimport sysÂ
# Function to calculate the possible# maximum cost of the arraydef 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 codeif __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 elementsusing System;Â
class GFG{  // Function to calculate the possible// maximum cost of the arraystatic 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 codepublic 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 arrayfunction 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 codevar arr = [2, 3, 9, 8, 4];document.write( getTotalTime(arr));Â
// This code is contributed by noob2000.</script> |
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.
Â
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



