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:
Minimize array length by repeatedly replacing pairs of unequal adjacent array elements by their sum
Next article icon

Minimize Array sum by replacing elements such that Relation among adjacent elements in maintained

Last Updated : 21 Apr, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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 can be smaller than the other.

Examples:

Input: arr[] = [ 2, 1, 3]
Output: 5
Explanation: The redesigned array will be [2, 1, 2]. Sum = 5 
Here arr[0] > arr[1] and arr[1] < arr[2] i.e. the relation among adjacent elements is unchanged. 
This is the minimum sum possible after replacements

Input: arr[] = [ 4, 5, 5]
Output: 4
Explanation: We can redesign array as [1, 2, 1]. 
arr[0] < arr[1] and arr[1] >= arr[2] which satisfies the condition of the question.
So the minimum possible sum is 1+2+1 = 4

 

Approach: This problem can be solved based on the following observation:

  • All the elements which are equal to or less than both its previous and next elements can be replaced by the smallest value i.e 1.
  • The smallest possible value for an element is dependent on the number of contiguous smaller elements in its left (say X) and in its right (say Y). So the smallest possible value is maximum between X+1 and Y+1.

Follow the steps mentioned below to solve the problem

  • Declare an array (say ans[]) to store the newly formed array after replacement and initialize all elements with 1.
  • Traverse arr[] from i = 1 to N-1. 
    • If arr[i] > arr[i-1], then set ans[i] to be ans[i-1] +1 because this sets the array element to have the value of number of contiguous smaller elements on left of arr[i].
  • Now traverse the array arr[] from i = N-2 to 0.
    • If arr[i] > arr[i + 1], then set ans[i] to be max(ans[i+1] +1, ans[i]) because it  sets the element to have value of the maximum number of contiguous elements on any side.
  • Return the sum of the newly formed array i.e ans[].

Below is the implementation of the above approach: 

C++
// C++ program for above approach #include <bits/stdc++.h> using namespace std;  int marks(vector<int>& A) {     // Making vector v and assigning 1     // to all elements     vector<int> ans(A.size(), 1);      // Traversing to check from left     // If element is of higher value we will     // add 1 to previous element     for (int i = 1; i < A.size(); i++)         if (A[i] > A[i - 1])             ans[i] = ans[i - 1] + 1;      // Traversing from right we will check     // whether it has value satisfying both     // side If element is of higher value we     // will add 1 to previous element     for (int i = A.size() - 2; i >= 0; i--)         if (A[i] > A[i + 1])             ans[i] = max(ans[i],                          ans[i + 1] + 1);      // Accumulating the array     // and returning the sum     int sum = 0;     for (int s : ans)         sum += s;     return sum; }  // Driver code int main() {     // Initializing a vector     vector<int> arr = { 4, 5, 5 };      // Function call     cout << marks(arr) << endl;     return 0; } 
Java
// Java program for above approach import java.io.*;  class GFG {    static int marks(int A[])   {     // Making vector v and assigning 1     // to all elements     int[] ans = new int[A.length];     for(int i = 0; i < A.length; i++)       ans[i] = 1;      // Traversing to check from left     // If element is of higher value we will     // add 1 to previous element     for (int i = 1; i < A.length; i++)       if (A[i] > A[i - 1])         ans[i] = ans[i - 1] + 1;      // Traversing from right we will check     // whether it has value satisfying both     // side If element is of higher value we     // will add 1 to previous element     for (int i = A.length - 2; i >= 0; i--)       if (A[i] > A[i + 1])         ans[i] = Math.max(ans[i],                           ans[i + 1] + 1);      // Accumulating the array     // and returning the sum     int sum = 0;     for (int i = 0; i < A.length; i++)       sum += ans[i];     return sum;   }    // Driver code   public static void main (String[] args)    {      // Initializing a vector     int arr[] = { 4, 5, 5 };      // Function call     System.out.println(marks(arr));   } }  // This code is contributed by hrithikgarg03188. 
Python3
# Python program for above approach def marks(A):        # Making vector v and assigning 1     # to all elements     ans = [1 for i in range(len(A))]      # Traversing to check from left     # If element is of higher value we will     # add 1 to previous element     for i in range(1,len(A)):         if (A[i] > A[i - 1]):             ans[i] = ans[i - 1] + 1      # Traversing from right we will check     # whether it has value satisfying both     # side If element is of higher value we     # will add 1 to previous element     for i in range(len(A)-2,-1,-1):         if (A[i] > A[i + 1]):             ans[i] = max(ans[i],ans[i + 1] + 1)      # Accumulating the array     # and returning the sum     sum = 0     for s in ans:         sum += s     return sum  # Driver code  # Initializing a vector arr = [ 4, 5, 5 ]  # Function call print(marks(arr))  # This code is contributed by shinjanpatra 
C#
// C# program for above approach using System;  public class GFG {   static int marks(int[] A)   {      // Making an array ans and assigning 1     // to all elements     int[] ans = new int[A.Length];     for (int i = 0; i < A.Length; i++)       ans[i] = 1;      // Traversing to check from left     // If element is of higher value we will     // add 1 to previous element     for (int i = 1; i < A.Length; i++)       if (A[i] > A[i - 1])         ans[i] = ans[i - 1] + 1;      // Traversing from right we will check     // whether it has value satisfying both     // side If element is of higher value we     // will add 1 to previous element     for (int i = A.Length - 2; i >= 0; i--)       if (A[i] > A[i + 1])         ans[i] = Math.Max(ans[i], ans[i + 1] + 1);      // Accumulating the array     // and returning the sum     int sum = 0;     for (int i = 0; i < A.Length; i++)       sum += ans[i];     return sum;   }    public static void Main(string[] args)   {     // Initializing a vector     int[] arr = { 4, 5, 5 };      // Function call     Console.Write(marks(arr));   } }  // This code is contributed by phasing17 
JavaScript
 <script>         // JavaScript code for the above approach         function marks(A)         {                      // Making vector v and assigning 1             // to all elements             let ans = new Array(A.length).fill(1);              // Traversing to check from left             // If element is of higher value we will             // add 1 to previous element             for (let i = 1; i < A.length; i++)                 if (A[i] > A[i - 1])                     ans[i] = ans[i - 1] + 1;              // Traversing from right we will check             // whether it has value satisfying both             // side If element is of higher value we             // will add 1 to previous element             for (let i = A.length - 2; i >= 0; i--)                 if (A[i] > A[i + 1])                     ans[i] = Math.max(ans[i],                         ans[i + 1] + 1);              // Accumulating the array             // and returning the sum             let sum = 0;             for (let s of ans)                 sum += s;             return sum;         }          // Driver code          // Initializing a vector         let arr = [4, 5, 5];          // Function call         document.write(marks(arr) + '<br>');      // This code is contributed by Potta Lokesh     </script> 

Output
4

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


Next Article
Minimize array length by repeatedly replacing pairs of unequal adjacent array elements by their sum

H

hemantrathore2705
Improve
Article Tags :
  • Greedy
  • DSA
  • Arrays
Practice Tags :
  • Arrays
  • Greedy

Similar Reads

  • 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
  • Minimize array length by repeatedly replacing pairs of unequal adjacent array elements by their sum
    Given an integer array arr[], the task is to minimize the length of the given array by repeatedly replacing two unequal adjacent array elements by their sum. Once the array is reduced to its minimum possible length, i.e. no adjacent unequal pairs are remaining in the array, print the count of operat
    6 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
  • 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
  • Minimize Array sum by replacing L and R elements from both end with X and Y
    Given an array A[] of N integers and 2 integers X and Y. The task is to minimize the sum of all elements of the array by choosing L and R and replacing the initial L elements with X and the R elements from the end with Y. Examples: Input: N = 5, X = 4, Y = 3, A[] = {5, 5, 0, 6, 3}Output: 14Explanati
    8 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
  • Minimize increment-decrement operation on adjacent elements to convert Array A to B
    Given two arrays A[] and B[] consisting of N positive integers, the task is to find the minimum number of increment and decrements of adjacent array elements of the array A[] required to convert it to the array B[]. If it is not possible, then print "-1". Examples: Input: A[] = {1, 2}, B[] = {2, 1}O
    11 min read
  • Maximize sum of given array by rearranging array such that the difference between adjacent elements is atmost 1
    Given an array arr[] consisting of N positive integers, the task is to maximize the sum of the array element such that the first element of the array is 1 and the difference between the adjacent elements of the array is at most 1 after performing the following operations: Rearrange the array element
    7 min read
  • Minimize the cost to make all the adjacent elements distinct in an Array
    Given two integer arrays arr[] and cost[] of size N, the task is to make all adjacent elements distinct at minimum cost. cost[i] denotes the cost to increment ith element by 1.Examples: Input: arr[] = {2, 2, 3}, cost[] = {4, 1, 5} Output: 2 Explanation: The second element has minimum increment cost.
    9 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