Find the largest element in an array generated using the given conditions | Java program to implement the above approach ; Function to generate the required array and to find and return the maximum array element ; Stores the array ; Base case ; Iterate over the indices ; If current index is even ; Otherwise ; Function to find and return the maximum array element ; If n is 0 ; If n is 1 ; Generates the required array ; Return maximum element of Arr ; Driver Code
import java . io . * ; import java . util . * ; import java . util . Arrays ; class GFG { static int [ ] findArray ( int n ) { int Arr [ ] = new int [ n + 1 ] ; Arr [ 0 ] = 0 ; Arr [ 1 ] = 1 ; for ( int i = 2 ; i <= n ; i ++ ) { if ( i % 2 == 0 ) { Arr [ i ] = Arr [ i / 2 ] ; } else { Arr [ i ] = Arr [ ( i - 1 ) / 2 ] + Arr [ ( i - 1 ) / 2 + 1 ] ; } } return Arr ; } static int maxElement ( int n ) { if ( n == 0 ) return 0 ; if ( n == 1 ) return 1 ; int [ ] Arr = findArray ( n ) ; int ans = Integer . MIN_VALUE ; for ( int i = 0 ; i < n ; i ++ ) { ans = Math . max ( ans , Arr [ i ] ) ; } return ans ; } public static void main ( String args [ ] ) { int N = 7 ; System . out . println ( maxElement ( N ) ) ; } }