【LeetCode】053. Maximum Subarray
2024-09-04 03:12:15
题目:
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
.
题解:
遍历所有组合,更新最大和。
Solution 1 (TLE)
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int n = nums.size(), result = nums[];
for(int i=; i<n; ++i) {
int tmp = nums[i];
result = max(tmp,result);
for(int j=i+; j<n; ++j) {
tmp += nums[j];
result = max(tmp,result);
}
}
return result;
}
};
可以看做动态规划的简略版,见Solution 5
Solution 2 ()
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int n = nums.size(), result = nums[], tmp = ;
for(int i=; i<n; ++i) {
tmp = max(tmp + nums[i], nums[i]);
result = max(result, tmp);
}
return result;
}
};
贪心算法:The idea is to find the largest difference between the sums when you summing up the array from left to right. The largest difference corresponds to the sub-array with largest sum
Solution 3 ()
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int sum = , minsum = , result = nums[], n = nums.size();
for(int i = ; i < n; i++) {
sum += nums[i];
if(sum - minsum > res) result = sum - minsum;
if(sum < minsum) minsum = sum;
}
return result;
}
};
分治法:
Solution 4 ()
DP算法:维护一个一维数组。
Solution 5 ()
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int n = nums.size();
vector<int> dp(n,);//dp[i] means the maximum subarray ending with nums[i];
dp[] = nums[];
int max = dp[]; for(int i = ; i < n; i++){
dp[i] = nums[i] + (dp[i - ] > ? dp[i - ] : );
max = Math.max(max, dp[i]);
}
return max;
}
};
最新文章
- Visual Studio Code 配置指南
- MongoDB学习笔记一—简介
- 解决安卓微信浏览器中location.reload 或者 location.href失效的问题
- WordPress基础:订阅源rss的使用
- 纸上谈兵:堆(heap)
- lost+found目录
- JDBC Connection
- Cocos2d-x标签文乱码问题
- Oracle 异常处理
- shell中exit命令不退出脚本
- hdu Repositoryti
- Https握手协议以及证书认证
- Python巡检Oracle表空间并邮件告警
- mvc中html导出成word下载-简单粗暴方式
- 使用HttpClient4.5实现HTTPS的双向认证
- Ubuntu 硬盘分区只读,重新挂载为读写分区之后,文件依然创建出错
- mysql创建外键注意事项
- C语言--第二周作业评分和总结(5班)
- Mysql 根据id查所有父级或子级
- linux-2.6.22.6内核启动分析之head.S引导段代码