A Maximum sum&&北邮月赛题

本文介绍了一种计算特定函数d(A)的方法,该函数应用于一组整数A中,任务是找到两组连续子序列,使得这两组子序列的元素之和最大。文中提供了一个高效的算法实现,并附带了示例输入输出,适用于算法竞赛或编程练习。
Time Limit:1000MSMemory Limit:65536KB

Description

Given a set of n integers: A={a1, a2,..., an}, we define a function d(A) as below:

d(A)=sum{a[s1]~a[t1]}+sum{a[s2]~a[t2]}

The rule is 1<=s1<=t1<s2<=t2<=n.

Your task is to calculate d(A).

Input

The input consists of T(<=30) test cases. The number of test cases (T) is given in the first line of the input.
Each test case contains two lines. The first line is an integer n(2<=n<=50000). The second line contains n integers: a1, a2, ..., an. (|ai| <= 10000).There is an empty line after each case.

Output

Print exactly one line for each test case. The line should contain the integer d(A).

Sample Input

1

10

1 -1 2 2 3 -3 4 -4 5 -5

Sample Output

13

Hint

In the sample, we choose {2,2,3,-3,4} and {5}, then we can get the answer.

Huge input,scanf is recommended

AC代码:

#include<iostream> #include<cstdio> #include<string.h> #define N 50001 using namespace std; int ss[N]; int main() { int T; scanf("%d",&T); while(T--) { int n,i; scanf("%d",&n); for(i=0;i<n;++i) scanf("%d",&ss[i]); int p=0; int s=0,e=0,t=0,max=0,sum=0; for(i=0;i<n;++i) { sum+=ss[i]; if(sum>max) { max=sum; s=t; e=i; } if(sum<0) { sum=0; t=i+1; } } p+=max; max=0; for(int i=s;i<=e;++i) ss[i]=0; for(int i=0;i<n;++i) { sum+=ss[i]; if(sum>max) max=sum; if(sum<0) sum=0; } printf("%d\n",p+max); }return 0; }

### 关于最大和算法及其解决方案 #### 最大子数组和问概述 最大子数组和问是找到一维数值数组中具有最大和的连续子数组。对于这个问,存在多种解决方法,其中Kadane算法是一种高效的方法[^1]。 该问的一个变种涉及处理循环数组的最大子数组和问,在这种情况下不仅考虑线性的子数组还考虑到跨越数组首尾相连形成的环形结构下的最优解[^2]。 #### 解决方案分析 针对常规的一维数组,可以采用线性时间复杂度\( O(n) \) 的动态规划方式来解决问。核心思想是在遍历过程中维护当前可能成为新起点的最佳局部解`thisSum`以及全局最佳解`maxSum`。每当遇到使得累积和变为负数的情况就重置起始位置;反之则更新全局最优解[^3]。 而对于包含正整数在内的任意整型序列而言,则需特别关注当所有元素均为负数的情形——此时应返回最大的单个元素而非默认值零。 Python实现了这一逻辑用于计算非环绕情况下的最大子数组和,并通过额外判断解决了环绕情形下可能出现的问: ```python class Solution: def maxSubarraySumCircular(self, A: list[int]) -> int: cur_max, global_max = 0, float('-inf') cur_min, global_min = 0, float('inf') total_sum = 0 for num in A: cur_max = max(cur_max + num, num) global_max = max(global_max, cur_max) cur_min = min(cur_min + num, num) global_min = min(global_min, cur_min) total_sum += num if global_max < 0: return global_max else: return max(global_max, total_sum - global_min) ``` 此代码片段综合运用了两种策略:一是直接查找最大子数组和;二是利用总和减去最小子数组和间接获得潜在更大的环绕区域内的最大子数组和。最终取两者之间的较大者作为结果输出。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值