Skip to content

Commit f1cdbbc

Browse files
author
zongyanqi
committed
add Easy_53_Maximum_Subarray
1 parent fcbe599 commit f1cdbbc

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

Easy_53_Maximum_Subarray.js

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
/**
2+
* Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
3+
*
4+
* For example, given the array [-2,1,-3,4,-1,2,1,-5,4],
5+
* the contiguous subarray [4,-1,2,1] has the largest sum = 6.
6+
*/
7+
8+
/**
9+
*
10+
* https://discuss.leetcode.com/topic/6413/dp-solution-some-thoughts
11+
*
12+
* @param {number[]} nums
13+
* @return {number}
14+
*/
15+
var maxSubArray = function (nums) {
16+
17+
var dp = [];
18+
var max = dp[0] = nums[0];
19+
20+
for (var i = 1; i < nums.length; i++) {
21+
dp[i] = nums[i] + (dp[i - 1] > 0 ? dp[i - 1] : 0);
22+
max = Math.max(dp[i], max);
23+
}
24+
25+
return max;
26+
27+
};
28+
29+
/**
30+
* https://discuss.leetcode.com/topic/5000/accepted-o-n-solution-in-java/11
31+
* @param nums
32+
* @returns {*}
33+
*/
34+
var maxSubArray = function (nums) {
35+
36+
var max = nums[0];
37+
var sum = nums[0];
38+
39+
for (var i = 1; i < nums.length; i++) {
40+
sum = sum > 0 ? (sum + nums[i]) : nums[i];
41+
max = Math.max(sum, max);
42+
}
43+
return max;
44+
45+
};
46+
47+
console.log(maxSubArray([1, 1, 1]) == 3);
48+
console.log(maxSubArray([-1, -1, -1]) == -1);
49+
console.log(maxSubArray([-2, 1, -3, 4, -1, 2, 1, -5, 4]) == 6);
50+
console.log(maxSubArray([-2, -1]) == -1);
51+
console.log(maxSubArray([-1]) == -1);
52+
console.log(maxSubArray([-1, 0]) == 0);
53+

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy