Skip to content

Commit b486aad

Browse files
authored
Create max-dot-product-of-two-subsequences.py
1 parent dbb67d7 commit b486aad

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
# Time: O(m * n)
2+
# Space: O(min(m, n))
3+
4+
class Solution(object):
5+
def maxDotProduct(self, nums1, nums2):
6+
"""
7+
:type nums1: List[int]
8+
:type nums2: List[int]
9+
:rtype: int
10+
"""
11+
if len(nums1) < len(nums2):
12+
return self.maxDotProduct(nums2, nums1)
13+
dp = [[0]*len(nums2) for i in xrange(2)]
14+
for i in xrange(len(nums1)):
15+
for j in xrange(len(nums2)):
16+
dp[i%2][j] = nums1[i]*nums2[j]
17+
if i and j:
18+
dp[i%2][j] += max(dp[(i-1)%2][j-1], 0)
19+
if i:
20+
dp[i%2][j] = max(dp[i%2][j], dp[(i-1)%2][j])
21+
if j:
22+
dp[i%2][j] = max(dp[i%2][j], dp[i%2][j-1])
23+
return dp[(len(nums1)-1)%2][-1]

0 commit comments

Comments
 (0)