【LeetCode】53. Maximum Subarray 最大子序和 解题报告(Python & C++ & Java)
作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/
题目地址:
https://leetcode.com/problems/maximum-subarray/#/description
题目描述
Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
Example:
Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
Follow up:
If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
题目大意
找出子数组的最大和。
解题方法
暴力解法
所谓暴力解法,就是找出所有子数组的最大的和。
为了快速求子数组的和,我们有个常用的技巧,就是用个 preSum[i] 数组表示在 i 位置之前的数组的和。即 preSum[i] = sum(num[0]...nums[i])。
然后使用两重循环,遍历所有的子数组,子数组和可以用 preSum[j] - preSum[i] 直接求出。
总的时间复杂度是 O(N ^ 2),可以通过。
C++代码如下:
class Solution {
public:
int maxSubArray(vector<int>& nums) {
const int N = nums.size();
vector<int> preSum(N + 1, 0);
for (int i = 0; i < N; ++i) {
preSum[i + 1] = preSum[i] + nums[i];
}
int res = INT_MIN;
for (int i = 0; i < N + 1; ++i) {
for (int j = i + 1; j < N + 1; ++j) {
res = max(res, preSum[j] - preSum[i]);
}
}
return res;
}
};
动态规划
明显的DP方法去解决。
通过构建一个和原长一样长的数组, dp 数组的含义是以 dp[i] 为结尾的最大子数组的和。
状态转移公式:
dp[i] = dp[i - 1] + nums[i]当 nums[i] >= 0 。dp[i] = nums[i]当 nums[i] < 0 。
题目求的最大子数组的和,就是 dp 数组的最大值。
Java 代码如下:
public class Solution {
public int maxSubArray(int[] nums) {
int len = nums.length;
int[] dp = new int[len];
dp[0] = nums[0];
int max = dp[0];
for(int i = 1; i < len; i++){
dp[i] = nums[i] + (dp[i -1] > 0 ? dp[i -1] : 0);
max = Math.max(max, dp[i]);
}
return max;
}
}
二刷,Python解法如下:
class Solution(object):
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums: return 0
N = len(nums)
cur, prev = 0, 0
res = float("-inf")
for i in range(N):
cur = nums[i] + (prev if prev > 0 else 0)
prev = cur
res = max(res, cur)
return res
三刷,C++解法如下:
class Solution {
public:
int maxSubArray(vector<int>& nums) {
const int N = nums.size();
int res = nums[0];
vector<int> dp(N, 0); // 以i为结尾的最大子数组的max subarray.
dp[0] = nums[0];
for (int i = 1; i < N; ++i) {
dp[i] = nums[i] + (dp[i - 1] > 0 ? dp[i - 1] : 0);
res = max(res, dp[i]);
}
return res;
}
};
日期
2017 年 5 月 2 日
2018 年 11 月 19 日 —— 周一又开始了
2020 年 4 月 3 日 —— 这个题是英文版leetcode的每日一题
【LeetCode】53. Maximum Subarray 最大子序和 解题报告(Python & C++ & Java)的更多相关文章
- LeetCode 53. Maximum Subarray最大子序和 (C++)
题目: Given an integer array nums, find the contiguous subarray (containing at least one number) which ...
- [LeetCode] 53. Maximum Subarray 最大子数组
Given an integer array nums, find the contiguous subarray (containing at least one number) which has ...
- [leetcode]53. Maximum Subarray最大子数组和
Given an integer array nums, find the contiguous subarray (containing at least one number) which has ...
- 53. Maximum Subarray最大子序和
网址:https://leetcode.com/problems/maximum-subarray/submissions/ 很简单的动态规划 我们可以把 dp[i] 表示为index为 i 的位置上 ...
- 【LeetCode】Maximum Subarray(最大子序和)
这道题是LeetCode里的第53道题. 题目描述: 给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和. 示例: 输入: [-2,1,-3,4,-1 ...
- [LeetCode] 53. Maximum Subarray 最大子数组 --动态规划+分治
Given an integer array nums, find the contiguous subarray (containing at least one number) which has ...
- 【LeetCode】26. Remove Duplicates from Sorted Array 解题报告(Python&C++&Java)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 双指针 日期 [LeetCode] https:// ...
- [array] leetcode - 53. Maximum Subarray - Easy
leetcode - 53. Maximum Subarray - Easy descrition Find the contiguous subarray within an array (cont ...
- 小旭讲解 LeetCode 53. Maximum Subarray 动态规划 分治策略
原题 Given an integer array nums, find the contiguous subarray (containing at least one number) which ...
随机推荐
- python20判断变量是否存在
python中检测某个变量是否有定义 第一种方法使用内置函数locals(): locals():获取已定义对象字典 'testvar' in locals().keys() 第二种方法使用内置函数d ...
- 毕业设计之LVS+keealive 负载均衡高可用实现
环境介绍 centos6.9最小化安装 主机名 IPADDR lvsA.load.quan.bbs 192.168.111.131 lvsB.load.quan.bbs 192.168.111.132 ...
- keyboard-interactive authentication with the ssh2 server failed 的SecureCRT报错解决
两种解决方法: 一.选定SSH2,选择Authentication,勾选Password,然后将该选项上移,挪到第一位即可 或者: 二.服务器端修改配置 默认情况/etc/ssh/sshd_confi ...
- msql_5.6.46编译问题
初始化数据库的时候, 使用mysql_install_db 必须是再mysql安装的目录下用相对路径去进行初始化 CentOs6.9必须先把/etc/my.cnf 先改为其他名字,之后再把安装目录下s ...
- kubernetes部署haproxy、keepalived为kube-apiserver做集群
也可以用nginx.keepalived做负载均衡,看大家的需求. # yum -y install haproxy keepalived haproxy的配置文件(三台一样): cat > / ...
- 『与善仁』Appium基础 — 17、元素定位工具(一)
目录 1.uiautomatorviewer介绍 2.uiautomatorviewer工具打开方式 3.uiautomatorviewer布局介绍 4.uiautomatorviewer工具的使用 ...
- 学习java 7.20
学习内容: Stream流 Stream流的生成方式 中间操作方法 终结操作方法 Stream流的收集操作 类加载 类加载器的作用 将.class文件加载到内存中,并为之生成对应的java.lang. ...
- 大规模 K8s 集群管理经验分享 · 上篇
11 月 23 日,Erda 与 OSCHINA 社区联手发起了[高手问答第 271 期 -- 聊聊大规模 K8s 集群管理],目前问答活动已持续一周,由 Erda SRE 团队负责人骆冰利为大家解答 ...
- A Child's History of England.2
They made boats of basket-work, covered with the skins of animals, but seldom, if ever, ventured far ...
- day02 Rsyuc备份服务器
day02 Rsyuc备份服务器 一.备份 1.什么是备份 备份就是把重要的数据或者文件复制一份保存到另一个地方,实现不同主机之间的数据同步 一般数据比较重要的情况下,数据如果丢失很容易找不回来了的, ...