循环数组的最大子段和
2016-11-27 13:32
204 查看
是个很有意思的东西,为什么呢,因为你很难计算循环
数组的最大字段,时间复杂度太高了,但是还是有思路的,哈哈哈
思路如下:ans=max(普通的最大子段和, 总和 – 普通的“最小子段和”)
为什么这么说呢?因为如果最大子段是断开的,那么说明最小子段和是连续的啊。如:
1 8 9 -1 -2 9 8 7
代码如下:
数组的最大字段,时间复杂度太高了,但是还是有思路的,哈哈哈
思路如下:ans=max(普通的最大子段和, 总和 – 普通的“最小子段和”)
为什么这么说呢?因为如果最大子段是断开的,那么说明最小子段和是连续的啊。如:
1 8 9 -1 -2 9 8 7
代码如下:
#include <stdio.h> #include <iostream> #include <math.h> #include <string.h> using namespace std; int main(){ int n; cin>>n; long long int num[n+1],dp[n+1]; memset(num,0,sizeof(num)); memset(dp,0,sizeof(dp)); long long int maxa=0,maxb=0,ans; for(int i=1;i<=n;i++)scanf("%lld",&num[i]); for(int i=1;i<=n;i++){ dp[i]=max(dp[i-1]+num[i],num[i]); if(maxa<dp[i])maxa=dp[i]; } memset(dp,0,sizeof(dp)); for(int i=1;i<=n;i++){ maxb+=num[i]; } long long int temp=1000000005; for(int i=1;i<=n;i++){ dp[i]=min(dp[i-1]+num[i],num[i]); if(temp>dp[i])temp=dp[i]; } maxb-=temp; ans=max(maxa,maxb); cout<<ans<<endl; }
相关文章推荐
- 动态规划--循环数组最大子段和
- 动态规划[入门]2-循环数组最大子段和
- 循环数组最大子段和(DP)
- 51nod 1050 循环数组最大子段和
- 循环数组的最大子段和
- 51nodLearning-dp入门之循环数组的最大子段和
- 循环数组最大子段和 ~~~~暴力出奇迹
- 1050 循环数组最大子段和
- 循环数组求最大子段和系列-----------方法1
- 1050 循环数组最大子段和
- nod 1050 循环数组最大子段和
- 51Nod 1050 循环数组最大子段和(dp)
- DP-循环数组最大子段和
- 51nod 1050 循环数组最大子段和 (dp)
- 51nod 1050 循环数组最大子段和 dp
- 动态规划-循环数组最大子段和
- 51 node 1050循环数组最大子段和
- 51nod 循环数组最大子段和(动态规划)
- 循环数组求最大子段和系列------方法2
- 循环数组最大子段和