剑指offer-面试题31 求连续子数组的最大和
来源:互联网 发布:建筑工地用工人员软件 编辑:程序博客网 时间:2024/06/07 14:44
#include<iostream>using namespace std;//常规方法int FindMaxSumOfSubArray1(int Array[], int length){ if(Array == NULL || length <= 0) { throw exception("ERROR"); } int nMax = 0; int nCurSum = 0; for(int i = 0; i< length; ++i) { if(nCurSum<=0) nCurSum = Array[i]; else nCurSum +=Array[i]; if(nCurSum > nMax) { nMax = nCurSum; } } return nMax;}int FindMaxSumOfSubArray2(int Array[], int length){ if(Array == NULL || length <= 0) { throw exception("ERROR"); } //运用动态规划,f(i)表示以array[i]结尾的子数组的最大和, 求出所有的f(i)的最大值就行 //如果f(i-1)<=0, 则f(i)=array[i], 否则f(i)=f(i-1)+array[i]; int nPre = Array[0]; //表示以前一个数结尾的序列的最大值 int nCur = 0; //表示以当前数结尾的序列的最大值 int nMax = 0x80000000;//代表int型最小的负数, 用于保存f(i)的最大值 for(int i = 1; i< length; ++i) { if(nPre <= 0) nCur = Array[i]; else nCur = nPre+Array[i]; nPre = nCur; if(nCur > nMax) nMax = nCur; } return nMax;}int main(){ int a[] = {1, -2, 3, 10, -4, 7, 2, -5}; cout<<FindMaxSumOfSubArray2(a, 8)<<endl;}
0 0
- 剑指offer 面试题31 求连续子数组的最大和
- 剑指offer-面试题31 求连续子数组的最大和
- 【面试题】剑指Offer-31-求连续子数组的最大和
- 剑指offer面试题 求数组中连续子数组的最大和
- 《剑指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实现)
- C++笔记(一)
- LeetCode036 Valid Sudoku
- 2017年产品经理之项目管理流程-全栈工程师熊盼
- x86-64和x86
- Java 知识点 集合+异常
- 剑指offer-面试题31 求连续子数组的最大和
- 计数排序-《算法导论》学习笔记八
- 1393: [Ceoi2008]knights
- [Ubuntu]常见问题手册
- 2.0第二章寄存器
- 冒泡排序的链表实现
- 剑指offer-面试题37 两个链表的第一个公共节点
- Myeclipse中Package的错误
- 剑指offer-面试题38 : 数字在排序数组中出现的次数