Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Maximum product Describe and analyze an algorithm that, given an array A of inte

ID: 3691215 • Letter: M

Question

Maximum product

Describe and analyze an algorithm that, given an array A of integers, finds the largest product of elements in a contiguous subarray A[i .. j].

This problem asks for dynamic programs. To answer this problem:

1. Briefly explain the recursive substructure of the problem.

2. Give the rule for filling in the dynamic programming table.

3. Give the asymptotic running time for the dynamic program.

4. Give the asymptotic space required for the dynamic program.

Then write out a complete implementation (in pseudo-code) for the algorithm.

Explanation / Answer

Hi below i have written a solution for your reference , hope you understand the logic :)

It is common to consider the DP(dynamic programming) method. And also since O(n^2) is NOT acceptable, there might be an O(n) solution.

To find the maximum product?
Note that, we need to consider two cases:
(1) negative numbers
Store the minimum product to handle the case that new element < 0. Because if current element < 0, the product of two negative numbers (new element, and minimum product before the new element) become positive.
(2) zeros
When meets zero, current max and min product become 0, new search is needed from the next element.

Therefore, we can write down to function to store both + and - products:

max_product = max{A[i]*min_product (when A[i]<0), A[i]*max_product (when A[i]>0), A[i] (when 0 occurs before A[i]) }.

min_product = min{A[i]*min_product, A[i]*max_product, A[i] }.

Because current sequence might start from any element, to get the final result, we also need to store the max product after each iteration "res = max(res, maxp);".

Code(C++):

class Solution {

public:

    int maxProduct(int A[], int n) {

        int res = A[0];

        int maxp = A[0];

        int minp = A[0];

        for (int i=1;i<n;i++){

            int tmpmax = maxp;

            int tmpmin = minp;

            maxp = max(max(tmpmax*A[i],tmpmin*A[i]),A[i]);

            minp = min(min(tmpmax*A[i],tmpmin*A[i]),A[i]);

            res = max(maxp,res);

        }

        return res;

    }

};