2.MaxSubArray-Leetcode
来源:互联网 发布:平板淘宝卖家 编辑:程序博客网 时间:2024/05/16 03:39
题目:最大连续子序列和
思路:动态规划
状态转移方程
f[j]=max{f[j-1]+s[j],s[j]}, 其中1<=j<=n
target = max{f[j]}, 其中1<=j<=n
class Solution {public: int maxSubArray(vector<int>& nums) { if(nums.size()==0)return -1; if(nums.size()==1)return nums[0]; vector<int> res_vec(nums.size()); res_vec[0]=nums[0]; int max_val = nums[0]; for(vector<int>::size_type i=1;i<nums.size();++i) { res_vec[i]=max(res_vec[i-1]+nums[i],nums[i]); if(max_val<res_vec[i])max_val = res_vec[i]; } return max_val; }};
下面给出一个类似的题:
给定一个整数的数组,相邻的数不能同时选,求从该数组选取若干整数,使得他们的和最大,要求只能使用o(1)的空间复杂度。要求给出伪码。
int getMax(int a[],int len){ int max1 = a[0];//表示maxSum(n-2); int max2 = a[0]>a[1]? a[0]:a[1]; //表示maxSum(n-1); int max3 = 0; // n for(int i =2; i<len; i++){ max3 = Max(a[i],Max(max1+a[i],max2)); max1 = max2; max2 = max3; } return max3;}
0 0
- 2.MaxSubArray-Leetcode
- leetcode maxSubArray
- maxSubArray
- maxSubArray
- maxSubArray
- [LeetCode]maxSubArray(最大子序列和!!!!)
- Ch4-MaxSubArray
- No11.week11 maxSubArray
- leetcode---2.Reverse Bits
- LeetCode---2.StringEasy
- 2.leetcode-Reverse Integer
- LeetCode ---2.Two Sum
- LeetCode---2.Two Sum
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode
- nyoj289苹果
- 点类
- Codeforces Round #303 (Div.2)-B. Equidistant String(模拟)
- 数据结构(10):二叉树基本功能的实现
- 关于linux安装Discuz的步骤
- 2.MaxSubArray-Leetcode
- android异常处理——try、catch、finally、throw、throws
- 菲波那契数
- 利用日志与secureCRT检查漏洞
- HDUOJ 1004 Let the Balloon Rise(字符串统计水题)
- 《机器学习实战》学习笔记(四):Naive Bayes
- JAVA网络编程
- 【LeetCode】87. Scramble String解法及注释
- C - Sorting Railway Cars