Minimum array elements to be changed to make Recaman 's sequence | C ++ implementation of the approach ; First term of the sequence is always 0 ; Fill remaining terms using recursive formula ; If arr [ i - 1 ] - i is negative or already exists ; Function that returns minimum changes required ; Set to store first n Recaman numbers ; Generate and store first n Recaman numbers ; Insert first n Recaman numbers to set ; If current element of the array is present in the set ; Return the remaining number of elements in the set ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int recamanGenerator ( int arr [ ] , int n ) { arr [ 0 ] = 0 ; for ( int i = 1 ; i <= n ; i ++ ) { int temp = arr [ i - 1 ] - i ; int j ; for ( j = 0 ; j < i ; j ++ ) { if ( ( arr [ j ] == temp ) temp < 0 ) { temp = arr [ i - 1 ] + i ; break ; } } arr [ i ] = temp ; } } int recamanArray ( int arr [ ] , int n ) { unordered_set < int > s ; int recaman [ n ] ; recamanGenerator ( recaman , n ) ; for ( int i = 0 ; i < n ; i ++ ) s . insert ( recaman [ i ] ) ; for ( int i = 0 ; i < n ; i ++ ) { auto it = s . find ( arr [ i ] ) ; if ( it != s . end ( ) ) s . erase ( it ) ; } return s . size ( ) ; } int main ( ) { int arr [ ] = { 7 , 11 , 20 , 4 , 2 , 1 , 8 , 6 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << recamanArray ( arr , n ) ; return 0 ; }