一个包含正整数和负整数的数组,找出和最大的子串.
来源:互联网 发布:遥控怎么打开网络电视 编辑:程序博客网 时间:2024/06/06 12:34
一个包含正整数和负整数的数组,找出和最大的子串.
Eg:int x[15] = {2,3,-5,5,6,-5,-1,14,9,-10,1,-1,75,4,-9};
给定一个整型数组a,求出最大连续子段之和
/*FindMaxSub.cpp*by wangzhihong*05/01/2007****************specification: find the substring in an array which has the maximun sum*/#include <iostream>using namespace std;int FindMaxSub(int array[],int len,int &start,int &end){ int max,sum; int i,temps; start=end=temps=max=sum=0; for(i=0;i<len;++i) { //there's no need to do this swap everytime when sum>max, //because if array[i]>0 the sum will always increase if(array[i]<0&&sum>max) { max=sum; start=temps; end=i-1; } //if the substring start from the next one, //we should not add the whole prestring because its sum is minus if(array[i]+sum<0) { sum=0; temps=i+1; continue; } sum+=array[i]; } //if the last one is used, //we should assign the max and end here if(sum>max) { max=sum; start=temps; end=i-1; } return max;}int FindMaxSub2(int array[],int len,int &start,int &end){int sum,max;start=end=0;max=sum=array[0];for (int i=1;i<len;++i){if(sum<=0 && summax){start=end=i;max=sum;}}else{sum+=array[i];if(sum>max){end=i;max=sum;}}}return max;}int main(void){ int *array; int len,start,end; int i; cin>>len; array=new int[len]; for(i=0;i<len;++i) cin>>array[i]; cout<<"Max Subvalue: "<<FindMaxSub(array,len,start,end)<<endl; cout<<"From: "<<start<<" To: "<<end<<endl; delete[] array; return 0;}
来自其评论:http://blog.sina.com.cn/s/blog_4bd02c41010008ue.html
- 一个包含正整数和负整数的数组,找出和最大的子串.
- 给定一个正整数和负整数组成的N*N矩阵,编写代码找出元素总和最大的子矩阵。
- 有一个数组,由正整数、负整数、零组成,求和最大的连续子数组
- 程序员面试金典——解题总结: 9.18高难度题 18.12给定一个正整数和负整数组成的N*M矩阵,编写代码找出元素总和最大的子矩阵。
- 找出一个数组里边和最大的子数组,输出最大和和子数组
- 求一个整数数组的子数组的最大和
- 在一个数组中找出和最大的一个连续的子数组串
- 找出连续子数组的最大和
- 包含n个整数的数组,返回该数组和为最大的子数组
- 给定一个由非负整数和整数m组成的数组,可以将该数组分成m个非空的连续子数组。 写一个算法来最小化这些m个子阵列之间的最大和。
- 给定一个数组,找出这个和最大的连续子数组的和
- 验证“负整数和正整数余运算”的语法法则
- c++ 程序 统计一个字符串内的正整数和负整数个数
- 求一个整数序列的和的最大子串
- 一个整数数组(正负,0),找出这个数组的最大子序列
- 求一个整数数组的连续子数组的最大和.
- 一个数组中找出连续子向量的最大和 分治算法 扫描算法O(n)
- 找出数组和最大的连续子序列
- JAVA基础 之 PreparedStatement
- 如何复位Freescale Power Architecture系列处理中的PCIe控制器
- ueditor编辑器乱码问题解决
- Java获取系统文件类型图标并显示在JSP上
- 嵌入式linux那点东东之整体框架
- 一个包含正整数和负整数的数组,找出和最大的子串.
- Linux下更改目录及其下的子目录和文件的访问权限
- VS2010的快捷键;VS2012变化的快捷键
- crontab 执行异常
- Java初学者不得不知的概念,JDK,JRE,JVM的区别?
- Ubuntu一般软件安装在什么目录下?
- adb shell dumpsys 命令 查看内存
- orcale用户操作语句
- java GC