DS - Maximum subcolumn sum

01-Complexity 1 maximum subcolumn sum problem (20 points)

givenA sequence of K integers { N1N2, ..., N ​K ​​} , "continuous subcolumns" are defined as { NiNi+1, ..., N ​j ​​} , where 1 i j K . The "maximum subcolumn sum" is defined as the largest sum of all consecutive subcolumn elements. For example, given the sequence { -2, 11, -4, 13, -5, -2 }, its consecutive sub-columns { 11, -4, 13 } have the largest sum of 20. You are now asked to write a program that computes the maximum subcolumn sum of a given sequence of integers.

This question is designed to test the performance of various algorithms on various data situations. The characteristics of each group of test data are as follows:

  • Data 1: Equivalent to the example, test the basic correctness;
  • data2: 10 2 random integers;
  • data 3: 10 3 random integers;
  • data 4: 10 4 random integers;
  • data 5: 10 5 random integers;

Input format:

input line 1 gives a positive integerK (1 0 0 0 0 0 ); given on line 2K integers separated by spaces.

Output format:

Print the maximum subcolumn sum in one row. If all integers in the sequence are negative, output 0.

Input sample:

6
-2 11 -4 13 -5 -2

Sample output:

20
Author: DS Course Group
Unit: Zhejiang University
Time limit: 50000ms
Memory Limit: 64MB

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

#define useIostream 1

struct ListNode
{
	int val;
	ListNode *next;
	ListNode(int x) :val(x), next(nullptr) { }
};

intmain()
{
	ListNode *head = new ListNode(0);
	ListNode *tail = head;

	int length = 0;

#if useIostream
	cin >> length;
#else
	fstream f("data.txt");
	f >> length;
#endif

	for (int i = 0; i<length; i++)
	{
		int val = 0;
#if useIostream
		cin >> val;
#else
		f >> val;
#endif
		tail->next = new ListNode(val);
		tail = tail->next;
	}

	ListNode *cur = head;
	ListNode *maxHead = nullptr;
	ListNode *maxTail = nullptr;
	int leftSum = 0;
	int maxSum = 0;
	while (cur)
	{
		if (leftSum < 0)
			leftSum = cur->val;
		else
			leftSum += cur->val;

		if (leftSum >= maxSum)
		{
			maxSum = leftSum;
			maxTail = cur;
		}
		cur = cur->next;
	}
	cout << maxSum << " " << maxHead->val << " " << maxTail->val;

	cur = head;
	while (cur)
	{
		ListNode *tmp = cur->next;
		delete cur;
		cur = tmp;
	}

#if !useIostream
	f.close();
	system("pause");
#endif
	return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325559561&siteId=291194637