Skip to content

Commit 2e4a23e

Browse files
committed
Add 1749
1 parent a64b542 commit 2e4a23e

File tree

3 files changed

+47
-0
lines changed

3 files changed

+47
-0
lines changed

Readme.md

+1
Original file line numberDiff line numberDiff line change
@@ -381,6 +381,7 @@
381381
| 1721 | Swapping Nodes in a Linked List | Medium | O(N) | O(1) | Linked List | | |
382382
| 1725 | Number Of Rectangles That Can Form The Largest Square | Easy | O(N) | O(1) | Greedy | | |
383383
| 1726 | Tuple with Same Product | Medium | O(N^2) | O(N) | Array, Hash Table | | |
384+
| 1749 | Maximum Absolute Sum of Any Subarray | Medium | O(N) | O(1) | Greedy | | |
384385
| | | | | | | | |
385386

386387
For premium problems, question description are available as screenshots [here](./premium-questions)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
#
2+
# @lc app=leetcode id=1749 lang=python3
3+
#
4+
# [1749] Maximum Absolute Sum of Any Subarray
5+
#
6+
7+
# @lc code=start
8+
# TAGS: Greedy
9+
class Solution:
10+
# 480 ms, 76.89%. Time: O(N). Space: O(N)
11+
def maxAbsoluteSum(self, nums: List[int]) -> int:
12+
def max_subarray(arr):
13+
ans = float("-inf")
14+
total = 0
15+
for val in arr:
16+
if total < 0:
17+
total = 0
18+
total += val
19+
ans = max(ans, total)
20+
return ans
21+
22+
val1 = max_subarray(nums)
23+
val2 = max_subarray(list(-n for n in nums))
24+
return max(abs(val1), abs(val2))
25+
26+
# 480 ms, 76.89%. 1 pass, Time: O(N). Space: O(1)
27+
def maxAbsoluteSum(self, nums: List[int]) -> int:
28+
max_sofar = float("-inf")
29+
min_sofar = float("inf")
30+
total_sum = total_sub = 0
31+
for val in nums:
32+
if total_sum < 0:
33+
total_sum = 0
34+
total_sum += val
35+
max_sofar = max(max_sofar, total_sum)
36+
37+
if total_sub > 0:
38+
total_sub = 0
39+
total_sub += val
40+
min_sofar = min(min_sofar, total_sub)
41+
return max(abs(min_sofar), abs(max_sofar))
42+
# @lc code=end
43+

testcases/1749

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
[1,-3,2,3,-4]
2+
[2,-5,1,-4,3,-2]
3+
[-7,-1,0,-2,1,3,8,-2,-6,-1,-10,-6,-6,8,-4,-9,-4,1,4,-9]

0 commit comments

Comments
 (0)