📌  相关文章
📜  通过将每个元素替换为相邻元素的总和而形成的Array的最大和

📅  最后修改于: 2021-05-17 20:57:30             🧑  作者: Mango

给定大小为N的数组arr [] ,任务是找到通过将原始数组的每个元素替换为相邻元素的总和而形成的Array的最大和。

例子:

方法:

  • 扫描阵列以选择总和最高的相邻对。
  • 从那以后,使用贪婪算法,选择左整数或右整数,以较大者为准。
  • 重复该过程,直到数组中只剩下一个元素。

下面是上述方法的实现:

C++
// C++ program to find the maximum sum
// of Array formed by replacing each
// element with sum of adjacent elements
  
#include 
using namespace std;
  
// Function to calculate the possible
// maximum cost of the array
int getTotalTime(vector& arr)
{
  
    // Check if array size is 0
    if (arr.size() == 0)
        return 0;
  
    // Initialise ;eft 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 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 ;eft 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 ;eft 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 ;eft 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


输出:
88

时间复杂度: O(N)

空间复杂度: O(N)