ZeroJudge B917: Maximum Product

UVa 11059 – Maximum Product

Given a series of integers S = {S1, S2, …, SN}, please find the maximum consecutive product. If no positive consecutive product is found, consider 0 as the maximum product.

Sample Inputs/Outputs

Sample Input(s)Sample Output(s)
EOF input. Each test case starts with a positive integer N, followed by N integers on the second line representing the numbers to multiply.Output the test case number and the maximum product, with one empty line between each set of data.
3
2 4 -3
5
2 5 -1 2 -1
Case #1: The maximum product is 8.
Case #2: The maximum product is 20.

Thought Process

Run a for loop that iterates over each starting point for the product. Within this loop, run another for loop from the starting point to N-1. Initialize a variable product to 1, and multiply each number encountered in the loop into the product, checking for the maximum value with each multiplication. This problem requires the use of Long Long Integers.

Sample Code-ZeroJudge B917: Maximum Product

#include <iostream>
#include <vector>
using namespace std;

int main() {
    cin.sync_with_stdio(0);
    cin.tie(0);
    int N, count = 1;
    while (cin >> N) {
        vector<int>num;
        long long int max = -999;
        for (int i = 0; i<N; i++) {
            int tmp;
            cin >> tmp;
            num.push_back(tmp);
        }
        for (int i = 0; i<N; i++) {
            long long int product = 1;
            for (int j = i; j<N; j++) {
                product *= num[j];
                if (product > max) max = product;
            }
        }
        cout << "Case #" << count << ": The maximum product is ";
        if (max < 0) cout << 0;
        else cout << max;
        cout << ".\n\n";
        count++;
    }
}

//ZeroJudge B917
//Dr. SeanXD

Comments