Maximum subarray product modulo M | C ++ program for above approach ; Function to find maximum subarray product modulo M and minimum length of the subarray ; Stores maximum subarray product modulo M and minimum length of the subarray ; Stores the minimum length of subarray having maximum product ; Traverse the array ; Stores the product of a subarray ; Calculate Subarray whose start index is i ; Multiply product by arr [ i ] ; If product greater than ans ; Update ans ; Update length ; Print maximum subarray product mod M ; Print minimum length of subarray having maximum product ; Drivers Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void maxModProdSubarr ( int arr [ ] , int n , int M ) { int ans = 0 ; int length = n ; for ( int i = 0 ; i < n ; i ++ ) { int product = 1 ; for ( int j = i ; j < n ; j ++ ) { product = ( product * arr [ i ] ) % M ; if ( product > ans ) { ans = product ; if ( length > j - i + 1 ) { length = j - i + 1 ; } } } } cout << " Maximum ▁ subarray ▁ product ▁ is ▁ " << ans << endl ; cout << " Minimum ▁ length ▁ of ▁ the ▁ maximum ▁ product ▁ " << " subarray ▁ is ▁ " << length << endl ; } int main ( ) { int arr [ ] = { 2 , 3 , 4 , 2 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int M = 5 ; maxModProdSubarr ( arr , N , M ) ; return 0 ; }