Maximum continuous subsequence Product

Source: Internet
Author: User

Problem description: given an integer sequence (which may have positive numbers, 0 and negative numbers), calculate the product of a continuous maximum subsequence. if the product is negative, the output is-1.
Analysis: assume that the array is a [] and the dynamic return is used directly to solve the problem. Considering the possible negative number, we use Max [I] to represent the product value of the maximum continuous subsequence ending with a [I, min [I] indicates the product value of the smallest continuous subsequence ending with a [I]. The state transition equation is:

Max [I] = max {A [I], Max [I-1] * A [I], Min [I-1] * A [I]}; min [I] = min {A [I], Max [I-1] * A [I], Min [I-1] * A [I]}; the initial status is Max [1] = min [1] = A [1]. The Code is as follows:

/* Given an integer array consisting of positive and negative numbers, 0 and positive numbers, the array subscript calculates the product of the maximum continuous subsequence from 1 and outputs this sequence, if the product of the maximum subsequence is negative, in this case, output-1 uses MAX [I] to represent the continuous subsequences with the largest product ending with a [I] And Min [I] to represent the continuous subsequences with the smallest product ending with a [I ]. because there are plural numbers, therefore, saving this is required */
Void longest_multiple (int * a, int N) {int * min = new int [n + 1] (); int * max = new int [n + 1] (); int * P = new int [n + 1] (); // initialize for (INT I = 0; I <= N; I ++) {P [I] =-1;} min [1] = A [1]; Max [1] = A [1]; int max_val = MAX [1]; for (INT I = 2; I <= N; I ++) {max [I] = max (I-1] * A [I], min [I-1] * A [I], a [I]); Min [I] = min (MAX [I-1] * A [I], min [I-1] * A [I], a [I]); If (max_val <MAX [I]) max_val = MAX [I];} If (max_val <0) printf ("% d",-1); else printf ("% d", max_val); // memory release Delete [] Max; Delete [] min ;}

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.