Skip to content

Commit 12fe826

Browse files
add Solution 53 by cpp
1 parent e8f92f8 commit 12fe826

File tree

1 file changed

+74
-0
lines changed

1 file changed

+74
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
/*
2+
* @lc app=leetcode.cn id=53 lang=cpp
3+
*
4+
* [53] 最大子序和
5+
*
6+
* https://leetcode-cn.com/problems/maximum-subarray/description/
7+
*
8+
* algorithms
9+
* Easy (46.59%)
10+
* Likes: 2144
11+
* Dislikes: 0
12+
* Total Accepted: 270.6K
13+
* Total Submissions: 524.4K
14+
* Testcase Example: '[-2,1,-3,4,-1,2,1,-5,4]'
15+
*
16+
* 给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。
17+
*
18+
* 示例:
19+
*
20+
* 输入: [-2,1,-3,4,-1,2,1,-5,4],
21+
* 输出: 6
22+
* 解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。
23+
*
24+
*
25+
* 进阶:
26+
*
27+
* 如果你已经实现复杂度为 O(n) 的解法,尝试使用更为精妙的分治法求解。
28+
*
29+
*/
30+
31+
#include <vector>
32+
33+
using std::vector;
34+
35+
// 贪心
36+
class Solution0 {
37+
public:
38+
int maxSubArray(vector<int>& nums) {
39+
if (nums.size() == 0) {
40+
return 0;
41+
}
42+
int result = nums[0];
43+
int temp = nums[0];
44+
for (int i = 1; i < nums.size(); i++) {
45+
if (temp >= 0) {
46+
temp += nums[i];
47+
} else {
48+
temp = nums[i];
49+
}
50+
result = std::max(result, temp);
51+
}
52+
return result;
53+
}
54+
};
55+
56+
// @lc code=start
57+
// 动态规划
58+
class Solution {
59+
public:
60+
int maxSubArray(vector<int>& nums) {
61+
if (nums.size() == 0) {
62+
return 0;
63+
}
64+
vector<int> dp = vector<int>(nums.size());
65+
dp[0] = nums[0];
66+
int result = nums[0];
67+
for (int i = 1; i < nums.size(); i++) {
68+
dp[i] = std::max(dp[i - 1] + nums[i], nums[i]);
69+
result = std::max(dp[i], result);
70+
}
71+
return result;
72+
}
73+
};
74+
// @lc code=end

0 commit comments

Comments
 (0)