算法之最大连续子序列之和之变形题目

来源:互联网 发布:sql2000备份50g数据库 编辑:程序博客网 时间:2024/06/06 13:04
Here are n numbers.
You have a magic first , you choose a interval [l,r],and then each Si(l<=i<=r) will be ( 10 – Si ) % 10.
You can use the magic at most once to make sum of all the numbers to be maximum.

What is the maximum sum you can get?

这是ACM题库的原要求,个人觉得算法分类其实并不是很多,但是巧的是如何将你已经会了的算法迁移到新的习题中解决新的问题。

int maxSum(int* A,int M){           if(M < 1)//元素个数不符合要求                 return 0;         if(M == 1)//元素个数为1时,返回A[0]                 return A[0];          int max = A[0],sum = A[0];//初始最大和为A[0],sum用于计算连续数据和          for(int i = 1; i < M ;i++){                  if(sum < 0)//去掉小于0的部分和                          sum = 0;                  sum += A[i];//重新开始计算连续数据和                 if(max < sum)//若所得新的连续数据和大于max,则重赋max                         max = sum ;          }          return max;  }
这是我在网上搜索的一段求解最大连续子序列之和的程序。相信大家一定很清楚为什么要这样写。

这是我针对这个问题所写的程序。

int maxSum(int A[],int n)
{
int sum = 0;int s = 0, max = 0, change = 0;
for (int i = 0; i < n; i++)
{
s += A[i];
}
sum = s;//求得数组之和
max = sum;
for (int i = 0; i < n; i++)
{
change = (10 - A[i]) % 10;
if (sum - A[i] + change < s)
sum = s;//若小于原数组之和,则舍弃前面的元素,从现在的i开始发生变幻
sum = sum - A[i] + change;//否则则变化sum,注意这个函数设计的s,sum,max三个变量的作用
if (max < sum)
max = sum;//保存所需要的最大值
}
return max;



int main()
{
int a[10];
for (int j = 0; j < 10; j++)
scanf_s("%d", &a[j]);
int max=maxSum(a, 10);
printf("%d\n", max);
}

主函数没有考虑过多用户需求,在ACM题目中往往要求有连续的输入及输出来实现控制数组数目,而不是限定数组数目,在这一点上后面还会继续修正。

如有考虑不周的问题欢迎指正

0 0
原创粉丝点击