Greatest contiguous sub | Java implementation of the approach ; Function that returns the sub - array ; Data - structure to store all the sub - arrays of size K ; Iterate to find all the sub - arrays ; Store the sub - array elements in the array ; Push the vector in the container ; Sort the vector of elements ; The last sub - array in the sorted order will be the answer ; Driver code ; Get the sub - array
import java . io . * ; import java . util . * ; class GFG { static ArrayList < Integer > findSubarray ( int a [ ] , int k , int n ) { ArrayList < ArrayList < Integer > > vec = new ArrayList < ArrayList < Integer > > ( ) ; for ( int i = 0 ; i < n - k + 1 ; i ++ ) { ArrayList < Integer > temp = new ArrayList < Integer > ( ) ; for ( int j = i ; j < i + k ; j ++ ) { temp . add ( a [ j ] ) ; } vec . add ( temp ) ; } Collections . sort ( vec , new Comparator < ArrayList < Integer > > ( ) { @ Override public int compare ( ArrayList < Integer > o1 , ArrayList < Integer > o2 ) { return o1 . get ( 0 ) . compareTo ( o2 . get ( 0 ) ) ; } } ) ; return vec . get ( vec . size ( ) - 1 ) ; } public static void main ( String [ ] args ) { int a [ ] = { 1 , 4 , 3 , 2 , 5 } ; int k = 4 ; int n = a . length ; ArrayList < Integer > ans = findSubarray ( a , k , n ) ; for ( int it : ans ) { System . out . print ( it + " ▁ " ) ; } } }