Skip to content

Commit c3956d7

Browse files
committed
Runtime: 47 ms (Top 48.8%) | Memory: 16.22 MB (Top 87.1%)
1 parent 6b92414 commit c3956d7

File tree

1 file changed

+19
-39
lines changed

1 file changed

+19
-39
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,44 +1,24 @@
1+
# Runtime: 47 ms (Top 48.8%) | Memory: 16.22 MB (Top 87.1%)
2+
3+
#####################################################################################################################
4+
# Problem: Wiggle Subsequence
5+
# Solution : Dynamic Programming
6+
# Time Complexity : O(n)
7+
# Space Complexity : O(1)
8+
#####################################################################################################################
9+
110
class Solution:
211
def wiggleMaxLength(self, nums: List[int]) -> int:
3-
# Top down with memo
4-
# Time: O(N2)
5-
dp = {}
6-
def wiggle(prevIndex, curIndex, sign):
7-
if curIndex >= len(nums):
8-
return 0
9-
10-
if (prevIndex, curIndex, sign) in dp:
11-
return dp[prevIndex, curIndex, sign]
12-
13-
diff = nums[prevIndex] - nums[curIndex]
14-
cur_sign = (diff > 0)
15-
include = exclude = 0
16-
17-
# if sign is different, we have two option, either take that element or ignore it
18-
if diff != 0 and (cur_sign is not sign):
19-
include = 1 + wiggle(curIndex, curIndex+1, cur_sign)
20-
exclude = wiggle(prevIndex, curIndex+1, sign)
21-
# since sign is same, here we have only one option, to exclude th curIndex
22-
else:
23-
# we can merge both exclude together to reduce lines, but keeping it separate for readability
24-
exclude = wiggle(prevIndex, curIndex+1, sign)
25-
26-
dp[prevIndex, curIndex, sign] = max(include, exclude)
27-
return dp[prevIndex, curIndex, sign]
28-
29-
return wiggle(0, 1, None) + 1
3012

31-
#--------------------------------------------------------------------------#
13+
positive, negative = 1, 1
14+
15+
if len(nums) < 2:
16+
return len(nums)
3217

33-
# Greedy Time: O(N)
34-
# Count all the changes of direction (peaks and vallyes)
35-
count = 1
36-
sign = 0
3718
for i in range(1, len(nums)):
38-
if nums[i-1] < nums[i] and sign != 1:
39-
sign = 1
40-
count += 1
41-
elif nums[i-1] > nums[i] and sign != -1:
42-
sign = -1
43-
count +=1
44-
return count
19+
if nums[i] > nums[i - 1]:
20+
positive = negative + 1
21+
elif nums[i] < nums[i - 1]:
22+
negative = positive + 1
23+
24+
return max(positive, negative)

0 commit comments

Comments
 (0)