Example 7-2 Maximum Product (Maximum Product, UVa 11059)

Welcome to visit my Uva problem solution directory https://blog.csdn.net/richenyunqi/article/details/81149109

Title description

Example 7-2 Description of Maximum Product (UVa 11059)

Interpretation

Enter a sequence S composed of n elements, and you need to find a continuous subsequence with the largest product. If the largest product is not a positive number, it should output 0 (indicating no solution). 1 ≤ n ≤ 18 1≤n≤181n18 − 10 ≤ S i ≤ 10 -10≤Si≤10 10S i10

algorithm design

Since the maximum n is only 18, the maximum result can be obtained by violently enumerating the product of all subsequences.

important point

  1. Since the absolute value of each element does not exceed 10 and does not exceed 18 elements, the maximum possible product will not exceed 1 0 18 10^{18}101 8 , need to use long long storage.
  2. A blank line is output after each test example

C++ code

#include <bits/stdc++.h>
using namespace std;
int main() {
    
    
    int n,a[20];
    for (int ii = 1; cin >> n; ++ii) {
    
    
        for(int i=0;i<n;++i)
            cin>>a[i];
        long long ans=0;
        for(int i=0;i<n;++i){
    
    
            for(int j=i;j<n;++j){
    
    
                long long p=1;
                for(int k=i;k<=j;++k)
                    p*=a[k];
                ans=max(ans,p);
            }
        }
        printf("Case #%d: The maximum product is %lld.\n\n", ii, ans);
    }
    return 0;
}

Guess you like

Origin blog.csdn.net/richenyunqi/article/details/100370019