算法之最大连续子序列之和之变形题目
来源:互联网 发布: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
- 算法之最大连续子序列之和之变形题目
- 算法进化历程之“最大连续子序列之和”
- 动态规划专题之最大连续子序列之和
- 动态规划专题讲义之最大连续子序列之和
- 最大连续子序列之和
- 最大连续子序列之和
- 最大连续子序列之和
- 最大连续子序列之和
- 最大连续子序列之和
- 最大子连续序列之和
- 最大连续子序列之和
- 求最大连续子序列之和 立方算法
- 最大连续子序列之和算法进化历程
- 最大连续子序列之和,最大连续子序列乘积
- 计算最大连续子序列之和
- 输出最大连续子序列之和
- 最大连续子序列之和的问题
- 最大和连续子序列的变形
- 聚类算法之混合高斯模型
- hdu 2079 选课时间(题目已修改,注意读题) (母函数)
- 在TStatusBar状态栏上自绘防闪烁
- 对Java类加载、实例化执行过程的理解
- 黑马程序员————List集合概述、Arrayist集合、Vector集合、LinkedList集合简述
- 算法之最大连续子序列之和之变形题目
- 理解了DirectShow播放原理
- Codec Engine 开发
- 输入输出--数值转换为字符串
- Android客户端从服务器端获取json数据并解析的实现代码
- CPSR寄存器
- 《自己动手写框架8》:高屋建瓴,理念先行
- C语言 变量作为函数定义中的实参写法
- 矩阵的 Frobenius 范数及其求偏导法则