LeetCode学习篇二十七——Maximum Subarray
来源:互联网 发布:网络监测软件 编辑:程序博客网 时间:2024/06/05 10:33
题目:Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
For example, given the array [-2,1,-3,4,-1,2,1,-5,4],
the contiguous subarray [4,-1,2,1] has the largest sum = 6.
难度:medium
解法一:动态规划(遍历数组全局最优和局部最优)
class Solution {public: int maxSubArray(vector<int>& nums) { if(nums.size() == 0) { return 0; } int maxi = INT_MIN; int temp = 0; for(int i = 0; i < nums.size(); i++) { if(temp < 0 ) temp = 0; temp += nums[i]; maxi = max(temp, maxi); } return maxi; }};
解法二:二分法
最大和子序列不是在左边的子序列,就是右边的子序列,或者中间的子序列
class Solution {public: int maxSum(vector<int> & nums, int l, int r) { if (l == r) return nums[l]; int mid = (l + r) / 2; int maxLeft = maxSum(nums, l, mid); int maxRight = maxSum(nums, mid + 1, r); int tL = 0, tR = 0; int maxL = INT_MIN, maxR = INT_MIN; for (int i = mid; i >= l; i--) { tL += nums[i]; if (tL > maxL) maxL = tL; } for (int i = mid + 1; i <= r; i++) { tR += nums[i]; if (tR > maxR) maxR = tR; } return maxLeft > maxRight ? (maxLeft > (maxL + maxR) ? maxLeft : (maxL + maxR)) : (maxRight > (maxL + maxR) ? maxRight : (maxL + maxR)); } int maxSubArray(vector<int>& nums) { return maxSum(nums, 0, nums.size() - 1); }};
0 0
- LeetCode学习篇二十七——Maximum Subarray
- LeetCode学习篇二十六——Maximum Product Subarray
- LeetCode——Maximum Subarray
- LeetCode——Maximum Subarray
- leetcode——Maximum Subarray
- LeetCode——Maximum Subarray
- LeetCode——Maximum subarray
- LeetCode—Maximum Product Subarray
- Leetcode学习(22)—— Maximum Subarray
- LeetCode——Maximum Product Subarray
- LeetCode——Maximum Product Subarray
- leetcode 053 —— Maximum Subarray
- leetcode 152 —— Maximum Product Subarray
- Maximum Product Subarray —— Leetcode
- leetcode——Maximum Product Subarray
- Leetcode题集——maximum-subarray
- leetcode题解——53. Maximum Subarray
- Leetcode——53. Maximum Subarray
- truncate和delete的区别
- HTML5系列文章【1】带你了解html主要标签及属性
- Springboot 之 解决IDEA读取properties配置文件的中文乱码问题
- windows下nginx安装、配置与使用
- Android与H5的交互
- LeetCode学习篇二十七——Maximum Subarray
- 了解一下winsock
- 一维数组,二维数组概念整理
- hive实例讲解实现in和not in子句
- PopUpWindow使用详解(一)——基本使用
- .NET调用命令行执行程序的相关问题
- vs2008下debug调试无错误,release调试出错怎么回事
- Qt 之 自定义按钮 在鼠标 悬浮、按下、松开后的效果
- 如何解决错误:A script behaviour has a different serialization layout when loading