Largest Ratio Contiguous subarray | C ++ program for the above approach ; Function to return maximum of two double values ; Check if a is greater than b then return a ; Function that returns the Ratio of max Ratio subarray ; Variable to store the maximum ratio ; Compute the product while traversing for subarrays ; Calculate the ratio ; Update max ratio ; Print the answer ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; double maximum ( double a , double b ) { if ( a > b ) return a ; return b ; } double maxSubarrayRatio ( double arr [ ] , int n ) { double maxRatio = INT_MIN ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i ; j < n ; j ++ ) { double ratio = arr [ i ] ; for ( int k = i + 1 ; k <= j ; k ++ ) { ratio = ratio / arr [ k ] ; } maxRatio = maximum ( maxRatio , ratio ) ; } } return maxRatio ; } int main ( ) { double arr [ ] = { 2 , 2 , 4 , -0.2 , -1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << maxSubarrayRatio ( arr , n ) ; return 0 ; }