forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchoidabom.ts
More file actions
32 lines (25 loc) · 767 Bytes
/
choidabom.ts
File metadata and controls
32 lines (25 loc) · 767 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// https://leetcode.com/problems/maximum-subarray/
// Time Limit Exceeded
function maxSubArray(nums: number[]): number {
const acc = []
const len = nums.length
for (let size = 1; size <= len; size++) {
for (let start = 0; start <= len - size; start++) {
const sub = nums.slice(start, start + size)
const sum = sub.reduce((acc, num)=> acc += num, 0)
acc.push(sum)
}
}
return acc.sort((a, b) => b - a)[0]
};
// TC: O(n)
// SC: O(n)
function maxSubArray(nums: number[]): number {
const dp = [...nums];
let max = dp[0];
for (let i = 1; i < nums.length; i++) {
dp[i] = Math.max(nums[i], dp[i - 1] + nums[i]);
max = Math.max(max, dp[i]);
}
return max;
}