
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Array Transformation in C++
Suppose there is an initial array arr, consider every day we produce a new array using the array of the previous day. On the i-th day, we will perform the following operations on the array of day i-1 to produce the array of the day i. The conditions are as follows −
If an element is smaller than both its left and its right adjacent values, then this element is incremented.
If an element is bigger than both its left and its right adjacent values, then this element is decremented.
The first and last elements will remain same.
After some days, the array does not change anymore. find that final array. So if the initial array is [6,2,3,4] then the output is [6,3,3,4]. On the first day, the array will be changed from [6,2,3,4] to [6,3,3,4], then no more operation will be performed.
To solve this, we will follow these steps −
- if array size is 2 or less than 2, then return array
- set flag := true
- while flag is true −
- set flag := false
- create one empty array called temp, and insert arr[0] into temp
- for i in range 1 to array size – 1
- if arr[i] < arr[i - 1] and arr[i] < arr[i + 1], then insert arr[i] + 1 into temp, and set flag as true
- otherwise when arr[i] > arr[i - 1] and arr[i] > arr[i + 1], then insert arr[i] – 1 into the temp, and set flag := true
- otherwise insert arr[i] into temp
- insert last element of arr into temp
- arr := temp
- return arr
Example(C++)
Let us see the following implementation to get a better understanding −
#include <bits/stdc++.h> using namespace std; #define push push_back void print_vector(vector<auto> v){ cout << "["; for(int i = 0; i<v.size(); i++){ cout << v[i] << ", "; } cout << "]"<<endl; } class Solution { public: vector<int> transformArray(vector<int>& arr) { if(arr.size()<=2)return arr; bool flag = true; while(flag){ flag = false; vector <int> temp; temp.push_back(arr[0]); for(int i = 1; i < arr.size()-1; i++){ if(arr[i]< arr[i-1] && arr[i]<arr[i+1]){ temp.push(arr[i]+1); flag = true; } else if(arr[i]> arr[i-1] && arr[i]>arr[i+1]){ flag = true; temp.push(arr[i]-1); } else temp.push(arr[i]); } temp.push_back(arr[arr.size()-1]); arr = temp; } return arr; } }; main(){ Solution ob; vector<int> v = {1,6,3,4,3,5}; print_vector(ob.transformArray(v)); }
Input
[1,6,3,4,3,5]
Output
[1,4,4,4,4,5]