两个不相连的子数组最大值
来源:互联网 发布:涿州网络兼职招聘网 编辑:程序博客网 时间:2024/05/16 06:55
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
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.
思路:
1. 从左到右求最大子数组和
2. 从右到左求最大子数组和
3. 利用1,2的结果得到两个子数组的最大和
- #include <stdio.h>
- #define MAX(a, b) ((a) > (b) ? (a) : (b))
- int n;
- int data[50001];
- int left_max[50001];
- int right_max[50001];
- void dp_max(int *data, int *max_arr)
- {
- int i = 0;
- int sum = 0;
- sum = max_arr[0] = data[0];
- for (i=1; i<n; i++)
- {
- sum = MAX(sum + data[i], data[i]);
- max_arr[i] = MAX(sum, max_arr[i-1]);
- }
- }
- void reverse_arr(int *data)
- {
- int size = n;
- int front = 0;
- int tail = n - 1;
- int tmp = 0;
- while (tail - front > 0)
- {
- tmp = data[front];
- data[front] = data[tail];
- data[tail] = tmp;
- tail--;
- front++;
- }
- }
- void printOut(int *max_arr)
- {
- int i;
- for (i=0; i<n; i++)
- printf("%d, ", max_arr[i]);
- printf("\n");
- }
- int handle()
- {
- dp_max(data, left_max);
- //printOut(left_max);
- reverse_arr(data);
- dp_max(data, right_max);
- //printOut(right_max);
- int i = 0;
- int tmp = 0;
- int max = left_max[0] + right_max[n-2];
- for (i=1; i<n-1; i++)
- {
- tmp = left_max[i] + right_max[n-2-i];
- if (tmp > max)
- max = tmp;
- }
- return max;
- }
- int main()
- {
- int T = 0;
- int i = 0;
- int j = 0;
- int ret = 0;
- scanf("%d", &T);
- for (i=0; i<T; i++)
- {
- scanf("%d", &n);
- for (j=0; j<n; j++)
- scanf("%d", &data[j]);
- ret = handle();
- printf("%d\n", ret);
- }
- }
- 两个不相连的子数组最大值
- 两个不相连的子数组最大值
- poj2479-在一个数组中求任意不相交的两个子数组之和的最大值
- 求一个数组中两个不重叠子数组和的差的最大值
- 子数组和最大值,以及不相交子数组其和之差的最大值问题
- 编程之美2.14扩展问题1 求子数组和的最大值(首尾可以相连)
- 编程之美2.14扩展问题1 求子数组和的最大值(首尾可以相连)
- 编程之美2.14扩展问题1 求子数组和的最大值(首尾可以相连)
- 最大连续子序列算法(数组的连续子数组最大和(首尾不相连))
- 求子数组的最大值
- 子数组之和的最大值
- 子数组之和的最大值
- 子数组之和的最大值
- 子数组之和的最大值
- 求子数组的最大值
- 子数组之和的最大值
- 子数组之和的最大值
- 子数组之和的最大值
- 1037. 在霍格沃茨找零钱(20)
- JAVA设计模式之生成器模式
- SharePoint 2013 Workflow Manager 1.0 卸载
- Qt中使用boost 库的另外一种方式
- 刷题的网站
- 两个不相连的子数组最大值
- Flac3D v3.0.261 1CD(完全安装版,功能强大的岩土分析软件)\
- 快速理解大小端
- 如何把一个eclipse安装包放到eclipse中
- linux 统计代码行数问题
- 如何在linux中搭建java环境
- 设计模式——模板模式
- Hibernate的学习之路二十八(唯一OID和对象导航的查询的方式)
- AC自动机