51Nod-1050-循环数组最大子段和
来源:互联网 发布:windows10 node sass 编辑:程序博客网 时间:2024/06/06 04:13
1050 循环数组最大子段和
基准时间限制:1 秒 空间限制:131072 KB 分值: 10 难度:2级算法题
收藏
关注
N个整数组成的循环序列a[1],a[2],a[3],…,a[n],求该序列如a[i]+a[i+1]+…+a[j]的连续的子段和的最大值(循环序列是指n个数围成一个圈,因此需要考虑a[n-1],a[n],a[1],a[2]这样的序列)。当所给的整数均为负数时和为0。
例如:-2,11,-4,13,-5,-2,和最大的子段为:11,-4,13。和为20。
Input
第1行:整数序列的长度N(2 <= N <= 50000)第2 - N+1行:N个整数 (-10^9 <= S[i] <= 10^9)
Output
输出循环数组的最大子段和。
Input示例
6-211-413-5-2
Output示例
20
51Nod-1050-循环数组最大子段和
思路:该题可用贪心来做,遍历数组,用sum记录当前及遍历过元素的值,若sum小于0则置0重新开始,记录sum的最大值。当由于数组为循环数组,故最大子段和分为两种情况:
一:在数组头尾之间,则可直接贪心AC。
二:在头尾相连的某一段,那么分析这种情况,由于该段为最大子段和,那么除该段的另一子段和则小于0,并且为最小的字段和,那么对于数组,只要对其元素求和,再减去最小子段和即为最大字段和。而最小子段和可将数组元素取反在求最大子段和。
#include<iostream>using namespace std;typedef long long LL; const int MAX_N=50005;int n;int a[MAX_N];LL f();int main(){ios::sync_with_stdio(false);cin.tie(0);while(cin>>n){LL ans,ans1,ans2,sum=0;for(int i=0;i<n;++i){cin>>a[i];sum+=a[i];}ans1=f();for(int i=0;i<n;++i)a[i]=-a[i];ans2=f();ans=max(ans1,ans2+sum); cout<<ans<<endl;} return 0;}LL f(){LL sum=0,ans=0;for(int i=0,k=0;i<n;++i){sum+=a[i];ans=max(ans,sum);if(sum<0)sum=0;}return ans;}
阅读全文
0 0
- 【循环数组最大子段和】51nod 1050 循环数组最大子段和
- 51nod 1050 循环数组最大子段和
- 51nod 1050 循环数组最大子段和 dp
- 51nod 1050 循环数组最大子段和
- 51nod 1050 循环数组最大子段和
- 51nod 1050 循环数组最大子段和
- 51nod 1050 循环数组最大子段和
- 51nod-1050 循环数组最大子段和
- 51nod 1050 循环数组最大子段和
- 51Nod 1050 循环数组最大子段和
- 51nod 1050 循环数组最大子段和
- 51Nod 1050 循环数组最大子段和
- 51nod 1050 循环数组最大子段和
- 51nod 1050 循环数组最大子段和
- 51nod 1050 循环数组最大子段和
- 51nod 1050 循环数组的最大子段和
- 51NOD 1050 循环数组最大子段和
- 51nod 1050 循环数组最大子段和
- 〖NOIP2003P〗栈
- Can't connect to local MySQL server through socket '/tmp/mysql.sock'
- 12.springboot使用redis的订阅功能实现消息队列
- 新建maven一直加载缓存 C:\Users\Administratol\AppData\Local\Temp\..
- 设计模式之禅PK之行为类1
- 51Nod-1050-循环数组最大子段和
- 求某个数组里连续子数组最大和的几个算法
- unity 4.x 全屏
- NOIP2008-03-传纸条
- socket
- demon14.4-14.5
- 写在年末 the end of 2017
- jQuery快速入门基础教程之效果(三)
- mysql命令行客户端快速建立数据库