Largest subvector and

Source: Internet
Author: User

HZ occasionally fooled non-computer students with some professional questions. Today, after the JOBDU test group was opened, he spoke again: in the Ancient One-dimensional pattern recognition, it is often necessary to calculate the largest sum of continuous subvectors. When all vectors are positive, the problem is well solved. However, if a vector contains a negative number, should it contain a negative number and expect the positive number next to it to compensate? For example: {6,-3,-0th,-15, 1, 3rd}, the maximum sum of continuous subvectors is 8 (starting from ). Will you be fooled by him? Input: multiple groups of data are input. Each group of test data includes two rows. The first act is an integer n (0 <= n <= 100000). When n = 0, the input ends. The next row contains n integers (we guarantee that all integers belong to [-]). Output: For each test case, three integers must be output in a single row, represents the largest continuous subvector and the subscript of the first element of the subvector and the subscript of the last element, respectively. If multiple subvectors exist, the smallest starting element is output. Sample input: 3-1-3-25-8 3 2 0 586-3-2 7-15 1 2 20 sample output: -1 0 0 10 1 4 8 0 3 idea: simple DP problem code AC: [cpp] # include <stdio. h> int main () {int data [100001]; int I, n, sum, max, start_idx, end_idx, now; while (scanf ("% d ", & n )! = EOF & n! = 0) {sum = 0; for (I = 0; I <n; I ++) {scanf ("% d", & data [I]); if (I = 0) {max = data [I]; now = 0; start_idx = 0; end_idx = 0;} if (sum <0) {sum = data [I]; now = I;} else {sum + = data [I];} if (sum> max) {max = sum; start_idx = now; end_idx = I;} else if (sum = max) {if (data [start_idx]> data [now]) {start_idx = now; end_idx = I ;}}} printf ("% d \ n", max, start_idx, end_idx);} return 0 ;}

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.