剑指offer面试题31:连续子数组的最大和
来源:互联网 发布:win32 api 知乎 编辑:程序博客网 时间:2024/05/16 19:31
问题描述:一个N个整数元素的一维数组(A[0],A[1],...,A[n-2],A[n-1]),这个数组当然有很多子数组,那么子数组之和的最大值是多少呢?
解题思路:定义两个变量,nStart表示以当前元素为首的子数组的最大值,nAll表示遍历到当前元素时最大子数组的值.从数组的尾元素开始遍历.有如下的递推公式:
算法伪代码实现如下:nStart = max(A[i], nStart + A[i]);
nAll = max(nStart, nAll);
int max(int x, int y) { return ((x > y) ? x : y); } int MaxSum(int* A, int n) { nStart = A[n-1]; nAll = A[n-1]; for (i = n-2; i >=0; i--) { nStart = max(A[i], nStart + A[i]); nAll = max(nStart, nAll); } return nAll; }上述解题思路是一种通用的实现方式,剑指offer种给出了另一种方法,不过有个前提条件就是:要处理的数组中既有正数又有负数.
这种情况下的解题思路为:定义两个变量,nCurSum表示当前连续子数组的最大值,nGreateSum表示遍历到当前元素时最大子数组的值.解题思路如下:
从数组开头开始遍历,每遍历一个元素之前首先查看nCurSum的正负号,如果小于或等于0,则说明之前累加的元素加上当前的元素值,肯定要小于当前的元素值,那么丢弃原来的累计值(这与数组元素的特性有关),将nCurSum的值至为当前元素值.
如果nCurSum值大于0,则令:nCurSum += pData[i].
每次处理完一个元素都要将nCurSum值与之前的nGreateSum值比较,并实时更新nGreateSum的值.
bool FindGreatestSumOfSubArray( int *pData, // an array unsigned int nLength, // the length of array int &nGreatestSum // the greatest sum of all sub-arrays){ // if the input is invalid, return false if((pData == NULL) || (nLength == 0)) return false; int nCurSum = nGreatestSum = 0; for(unsigned int i = 0; i < nLength; ++i) { nCurSum += pData[i]; // if the current sum is negative, discard it if(nCurSum < 0) nCurSum = 0; // if a greater sum is found, update the greatest sum if(nCurSum > nGreatestSum) nGreatestSum = nCurSum; } // if all data are negative, find the greatest element in the array if(nGreatestSum == 0) { nGreatestSum = pData[0]; for(unsigned int i = 1; i < nLength; ++i) { if(pData[i] > nGreatestSum) nGreatestSum = pData[i]; } } return true;}
0 0
- 《剑指Offer》面试题:连续子数组的最大和
- [剑指offer][面试题31]连续子数组的最大和
- 剑指offer面试题31:连续子数组的最大和
- 剑指Offer:面试题31 连续子数组的最大和
- 剑指offer 面试题31 求连续子数组的最大和
- 《剑指Offer》学习笔记--面试题31:连续子数组的最大和
- 【剑指Offer学习】【面试题31:连续子数组的最大和】
- 剑指Offer面试题31(java版):连续子数组的最大和
- 【剑指offer】5.2时间效率——面试题31:连续子数组的最大和
- 剑指offer代码解析——面试题31连续子数组的最大和
- 剑指offer-面试题31:连续子数组的最大和
- 剑指offer 面试题31:连续子数组的最大和 题解
- 剑指offer之面试题31连续子数组的最大和
- 剑指Offer:面试题31——连续子数组的最大和(java实现)
- 剑指Offer----面试题31:连续子数组的最大和
- 剑指offer面试题31:连续子数组的最大和
- 剑指offer--面试题31:连续子数组的最大和
- 连续子数组的最大和(剑指Offer 面试题31)
- Generate Parentheses
- python搭建web server
- 行为类模式大PK(总结)
- 一个 Linux 上分析死锁的简单方法
- HDU 3290 The magic apple tree DFS
- 剑指offer面试题31:连续子数组的最大和
- 变脸不变质的桥梁模式(Bridge Pattern)
- hdu 4135 Co-prime (组合数学:容斥定理+欧拉函数)
- 安卓基础学习-搭建开发环境和HelloWord(一)
- python 的日志logging模块学习
- 网络层相关概念
- 2015年华为提前招聘机试题--输出最大的三位数
- CSS自定义字体(@font-face选择符)
- Android输入子系统浅析(一)