Open In App

Minimizing Sum with Neighbor Value Priority in Array Transformation

Last Updated : 28 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array arr[] of length n, where arr[i] represents some value. You have to create an array result[] of length n, such that it follows both conditions given below and the task is to find the minimum sum of the result[] while ensuring that these rules are satisfied.

  • result[i] >= 1, for all i, such that 0 <= i <= n
  • result[i] with a higher arr[i] get more value than their neighbors.

Examples:

Input: arr = {1,0,2}
Output: 5
Explanation: We can create result[] = {2, 1, 2}, it follows both given conditions.

Input: arr = {1,2,2}
Output: 4
Explanation: We can create result[] = {1, 2, 1}, it follows both given conditions.

Input: arr = {1,2,3}
Output: 4
Explanation: We can create result[] = {1, 2, 3}, it follows both given conditions.

Approach: To solve the problem follow the below idea:

Our aim to ensure that elements with higher values receive more items than their neighbors, while satisfying the constraint that each element receives at least one item. To achieve this, we have to calculates left and right counts for each element and then computes the minimum sum of items needed to meet these conditions.

Step-by-step approach:

  • Create a variable totalSum for answer.
  • Create two array, leftCounts[] and rightCounts[], both of size n, and initialize them to 1.
  • Iterate from starting indexing of arr[].
    • If the current element is greater than the previous one, update leftCounts for the current element as leftCounts[i] = leftCounts[i – 1] + 1.
  • Iterate arr[] in reverse order.
    • If the current element is greater than the next one, update rightCounts for the current element as rightCounts[i] = rightCounts[i + 1] + 1.
  • Iterate through each element of arr.
    • Add the maximum value between leftCounts[i] and rightCounts[i] to totalSum.
  • Return totalSum as the minimum sum needed.

Below is the implementation of the above approach:

C++




// C++ code for the above approach:
#include <bits/stdc++.h>
using namespace std;
 
// Function to calculate the minimum sum of
// elements needed to satisfy the
// given conditions.
int minimumSum(vector<int>& arr)
{
    int n = arr.size();
 
    // Initialize vectors to store 2nd
    // condition for left Neighbour and
    // right Neighbour.
    vector<int> resultLeft(n, 1), resultRight(n, 1);
 
    // Initialize the total sum.
    int totalSum = 0;
 
    // Calculate the count of items to the
    // left of each element that should
    // receive more items.
    for (int i = 0; i < n; i++) {
        if (i - 1 >= 0 && arr[i] > arr[i - 1]) {
            resultLeft[i] = resultLeft[i - 1] + 1;
        }
 
        // Calculate the count of items to
        // the right of each element that
        // should receive more items.
        if (n - i < n && arr[n - i - 1] > arr[n - i]) {
            resultRight[n - i - 1] = resultRight[n - i] + 1;
        }
    }
 
    // Calculate the total sum by taking the
    // maximum count between left and right
    // for each element.
    for (int i = 0; i < n; i++) {
        totalSum += max(resultLeft[i], resultRight[i]);
    }
 
    // Return the minimum sum of
    // elements needed.
    return totalSum;
}
 
// Drivers code
int main()
{
 
    vector<int> arr = { 1, 2, 3 };
 
    int minSum = minimumSum(arr);
 
    // Function Call
    cout << minSum << endl;
 
    return 0;
}


Java




import java.util.*;
 
class GFG {
 
    // Function to calculate the minimum sum of
    // elements needed to satisfy the given conditions.
    static int minimumSum(int[] arr) {
        int n = arr.length;
 
        // Initialize arrays to store 2nd
        // condition for left Neighbour and
        // right Neighbour.
        int[] resultLeft = new int[n];
        int[] resultRight = new int[n];
 
        Arrays.fill(resultLeft, 1);
        Arrays.fill(resultRight, 1);
 
        // Initialize the total sum.
        int totalSum = 0;
 
        // Calculate the count of items to the
        // left of each element that should
        // receive more items.
        for (int i = 0; i < n; i++) {
            if (i - 1 >= 0 && arr[i] > arr[i - 1]) {
                resultLeft[i] = resultLeft[i - 1] + 1;
            }
 
            // Calculate the count of items to
            // the right of each element that
            // should receive more items.
            if (n - i < n && arr[n - i - 1] > arr[n - i]) {
                resultRight[n - i - 1] = resultRight[n - i] + 1;
            }
        }
 
        // Calculate the total sum by taking the
        // maximum count between left and right
        // for each element.
        for (int i = 0; i < n; i++) {
            totalSum += Math.max(resultLeft[i], resultRight[i]);
        }
 
        // Return the minimum sum of elements needed.
        return totalSum;
    }
 
    // Drivers code
    public static void main(String[] args) {
        int[] arr = { 1, 2, 3 };
 
        int minSum = minimumSum(arr);
 
        // Function Call
        System.out.println(minSum);
    }
}


Python3




def minimum_sum(arr):
    n = len(arr)
 
    # Initialize vectors to store 2nd
    # condition for left Neighbour and
    # right Neighbour.
    result_left = [1] * n
    result_right = [1] * n
 
    # Initialize the total sum.
    total_sum = 0
 
    # Calculate the count of items to the
    # left of each element that should
    # receive more items.
    for i in range(n):
        if i - 1 >= 0 and arr[i] > arr[i - 1]:
            result_left[i] = result_left[i - 1] + 1
 
        # Calculate the count of items to
        # the right of each element that
        # should receive more items.
        if n - i < n and arr[n - i - 1] > arr[n - i]:
            result_right[n - i - 1] = result_right[n - i] + 1
 
    # Calculate the total sum by taking the
    # maximum count between left and right
    # for each element.
    for i in range(n):
        total_sum += max(result_left[i], result_right[i])
 
    # Return the minimum sum of elements needed.
    return total_sum
 
# Drivers code
if __name__ == "__main__":
    arr = [1, 2, 3]
    min_sum = minimum_sum(arr)
 
    # Function Call
    print(min_sum)


C#




using System;
 
class GFG
{
    // Function to calculate the minimum sum of
    // elements needed to satisfy the given conditions.
    static int MinimumSum(int[] arr)
    {
        int n = arr.Length;
 
        // Initialize arrays to store 2nd
        // condition for left Neighbour and
        // right Neighbour.
        int[] resultLeft = new int[n];
        int[] resultRight = new int[n];
 
        // Fill arrays with default values of 1.
        Array.Fill(resultLeft, 1);
        Array.Fill(resultRight, 1);
 
        // Initialize the total sum.
        int totalSum = 0;
 
        // Calculate the count of items to the
        // left of each element that should
        // receive more items.
        for (int i = 0; i < n; i++)
        {
            if (i - 1 >= 0 && arr[i] > arr[i - 1])
            {
                resultLeft[i] = resultLeft[i - 1] + 1;
            }
 
            // Calculate the count of items to
            // the right of each element that
            // should receive more items.
            if (n - i < n && arr[n - i - 1] > arr[n - i])
            {
                resultRight[n - i - 1] = resultRight[n - i] + 1;
            }
        }
 
        // Calculate the total sum by taking the
        // maximum count between left and right
        // for each element.
        for (int i = 0; i < n; i++)
        {
            totalSum += Math.Max(resultLeft[i], resultRight[i]);
        }
 
        // Return the minimum sum of elements needed.
        return totalSum;
    }
 
    // Driver code
    public static void Main(string[] args)
    {
        int[] arr = { 1, 2, 3 };
 
        int minSum = MinimumSum(arr);
 
        // Function Call
        Console.WriteLine(minSum);
    }
}


Javascript




function minimumSum(arr) {
  const n = arr.length;
 
  // Initialize vectors to store 2nd
  // condition for left Neighbour and
  // right Neighbour.
  const resultLeft = Array(n).fill(1);
  const resultRight = Array(n).fill(1);
 
  // Initialize the total sum.
  let totalSum = 0;
 
  // Calculate the count of items to the
  // left of each element that should
  // receive more items.
  for (let i = 0; i < n; i++) {
    if (i - 1 >= 0 && arr[i] > arr[i - 1]) {
      resultLeft[i] = resultLeft[i - 1] + 1;
    }
 
    // Calculate the count of items to
    // the right of each element that
    // should receive more items.
    if (n - i < n && arr[n - i - 1] > arr[n - i]) {
      resultRight[n - i - 1] = resultRight[n - i] + 1;
    }
  }
 
  // Calculate the total sum by taking the
  // maximum count between left and right
  // for each element.
  for (let i = 0; i < n; i++) {
    totalSum += Math.max(resultLeft[i], resultRight[i]);
  }
 
  // Return the minimum sum of elements needed.
  return totalSum;
}
 
// Drivers code
const arr = [1, 2, 3];
const minSum = minimumSum(arr);
 
// Function Call
console.log(minSum);
 
// This code is contributed by shivamgupta310570


Output

6







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



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads