Home >Backend Development >C++ >C++ program: find array after removing maximum value C++ program to find array after removing maximum value
Suppose we have an array A containing n elements and another value k. We want to perform k operations. An operation has the form:
Assume d is the maximum value of the array
For each index i from 1 to n, add A Replace [i] with d - A[i]
We need to find the final sequence.
An array in a data structure is a finite collection of elements of a specific type. Arrays are used as Store elements of the same type in consecutive memory locations. An array is allocated A specific name and referred to by that name in various programming languages To access an element of an array, an index is required. We use the term "name[i]" to Access a specific element at position 'i' in array 'name'. various data structures For example, stacks, queues, heaps, and priority queues can all be implemented using arrays. Operates on Arrays include insert, delete, update, traverse, search, and sort operations. access Links below are for further reading.
https://www.tutorialspoint.com/data_structures_algorithms/array_data_structure.htm
So, if the input to our problem is A = [5, -1, 4, 2, 0]; k = 19., then the output will be [0, 6, 1, 3, 5] because d is 5.
To solve this problem, we will follow the following 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]
Let us look at the following implementation for better understanding Understand −
#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); }
{ 5, -1, 4, 2, 0 }, 19
0, 6, 1, 3, 5,
The above is the detailed content of C++ program: find array after removing maximum value C++ program to find array after removing maximum value. For more information, please follow other related articles on the PHP Chinese website!