2.13 Maximum multiplication of sub-arrays

Source: Internet
Author: User

Topic:

Given a shaped array of length n, only multiplication is allowed and no division can be used. Calculates the largest group of products in a combination of any number of N-1.


Method One:

#include <iostream> #define MAXN 10000using namespace Std;int N, A[maxn], S[MAXN], T[MAXN], p[maxn];//s[i] The product of the first element of the array//t[i] represents the product of N-i elements after the array//p[i] = s[i-1] * t[i+1];   P[i] indicates that the array, in addition to the first element, is the product of the other N-1 elements//s[i]=a[0]*a[1]* ... A[i], t[i]=a[i]*a[i+1]* ... a[n-1]//P[i] = s[i-1] * t[i+1]. int main () {cin >> n;for (int i = 0; i < n; ++i) cin >> A[i];int SV = 1, TV = 1;for (int i = 0; i < n; ++i ) {Int J = n-i-1;sv *= a[i];tv *= a[j];s[i] = sv;t[j] = TV;} int maxnum = p[0] = t[1];    P[0] and t[1] represent the values that are multiplied by the remaining N-1 elements except for the first element. for (int i = 1; i < n; ++i) {p[i] = s[i-1] * t[i+1];maxnum = Maxnum < P[i]? P[i]: maxnum;} cout << maxnum << endl;return 0;}

Method Two:

Ideas:

The maximal product problem of Subarray can be divided into the following situations.

1. There are more than one zero in the array, the maximum product is 0;

2. There is only one 0 in the array, and an odd number of negative numbers, the maximum product must be 0;

3. There is only one 0 in the array, and an even number of negative numbers, the maximum product is the product of the element that removes 0;

4. There is no zero in the array, and there are odd numbers of negative numbers, then the maximum product is the product of the negative number minus the absolute value;

5. There is no zero in the array, and an even number of negative numbers, the maximum product is the product of the lowest positive number removed.


So the number of positive numbers in the array, the number of negative numbers, and the number of 0! This is the simplest way!


2.13 Maximum multiplication of sub-arrays

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.