Greatest contiguous sub | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; vector < int > findSubarray ( int a [ ] , int k , int n ) { vector < vector < int > > vec ; for ( int i = 0 ; i < n - k + 1 ; i ++ ) { vector < int > temp ; for ( int j = i ; j < i + k ; j ++ ) { temp . push_back ( a [ j ] ) ; } vec . push_back ( temp ) ; } sort ( vec . begin ( ) , vec . end ( ) ) ; return vec [ vec . size ( ) - 1 ] ; } int main ( ) { int a [ ] = { 1 , 4 , 3 , 2 , 5 } ; int k = 4 ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; vector < int > ans = findSubarray ( a , k , n ) ; for ( auto it : ans ) cout << it << " ▁ " ; }