C++ Program to find array after removal from maximum


Suppose we have an array A with n elements and another value k. We want to perform k following operations. One operation is like −

  • Let d is the maximum value of the array

  • For every index i from 1 to n, replace A[i] with d - A[i]

We have to find the final sequence.

Problem Category

An array in the data structure is a finite collection of elements of a specific type. Arrays are used to store elements of the same type in consecutive memory locations. An array is assigned a particular name and it is referenced through that name in various programming languages. To access the elements of an array, indexing is required. We use the terminology 'name[i]' to access a particular element residing in position 'i' in the array 'name'. Various data structures such as stacks, queues, heaps, priority queues can be implemented using arrays. Operations on arrays include insertion, deletion, updating, traversal, searching, and sorting operations. Visit the link below for further reading.

https://www.tutorialspoint.com/data_structures_algorithms/array_data_structure.htm

So, if the input of our problem is like A = [5, -1, 4, 2, 0]; k = 19., then the output will be [0, 6, 1, 3, 5], because the d is 5.

Steps

To solve this, we will follow these steps −

n := size of A
m := -inf
t := -inf
for initialize i := 0, when i < n, update (increase i by 1), do:
   m := maximum of m and A[i]
for initialize i := 0, when i < n, update (increase i by 1), do:
   A[i] := m - A[i]
   t := maximum of t and A[i]
if k mod 2 is same as 1, then:
   for initialize i := 0, when i < n, update (increase i by 1), do:
      print A[i]
   Otherwise
      for initialize i := 0, when i < n, update (increase i by 1), do:
         A[i] := t - A[i]
         print A[i]

Example

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;
void solve(vector<int> A, int k){
   int n = A.size();
   int m = -999;
   int t = -999;
   for (int i = 0; i < n; i++)
      m = max(m, A[i]);
   for (int i = 0; i < n; i++)
      A[i] = m - A[i], t = max(t, A[i]);
   if (k % 2 == 1)
      for (int i = 0; i < n; i++)
         cout << A[i] << ", ";
   else
      for (int i = 0; i < n; i++)
         A[i] = t - A[i], cout << A[i] << ", ";
}
int main(){
   vector<int> A = { 5, -1, 4, 2, 0 };
   int k = 19;
   solve(A, k);
}

Input

{ 5, -1, 4, 2, 0 }, 19

Output

0, 6, 1, 3, 5,

Updated on: 08-Apr-2022

72 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements