C Program to Split the Highest value in the Array

  • Take an array of length n where all the numbers are nonnegative and unique.
  • Find the element in the array possessing the highest value.
  • Split the element into two parts where the first part contains the next highest value in the array and the second part holds the required additive entity to get the highest value.
  • Print the array where the highest value gets split into those two parts.
  • Split the Highest value in the Array

For example:

the given array is: 4 8 6 3 2
the updated array is: 4 6 2 6 3 2

Explanation :

  • In the input the highest value is 8, it is split into two parts with the next highest value which is 6 and the remaining value is 2

Input Format:

  • First-line has an integer that denotes the size of the array
  • Second-line contains the elements of the array delimited by space.

Constraints :
1 <= N <= 100
1 <= arr[i] <= 1000

Output Format:

Print the updated array sample Input 1

5
4 8 6 3 2

Sample Output 1

4 6 2 6 3 2 

Code:

#include<stdio.h>
int main() {
    int n;
    scanf("%d",&n);
    int arr[n];
    for(int i=0; i<n; i++) {
        scanf("%d",&arr[i]);
    }
    int maxInd = 0;
    for(int i=1; i<n; i++) {
        if(arr[i]>arr[maxInd]) {
            maxInd = i;
        }
    }
    int secondMax = 0;
    for(int i=0; i<n; i++) {
        if(i != maxInd && arr[i]>secondMax) {
            secondMax = arr[i];
        } 
    }
    int b = arr[maxInd]-secondMax;
    int ans[n+1];
    int ind = 0;
    for(int i=0; i<n; i++) {
        if(i == maxInd) {
            ans[ind++] = secondMax;
            ans[ind++] = b;
        } else {
            ans[ind++] = arr[i]; 
        }
    }
    for(int i=0; i<n+1; i++) {
        printf("%d ",ans[i]);
    }
}
Code language: C/AL (cal)

Leave a Comment