0% found this document useful (0 votes)
9 views

Dynamic Programming 2

Uploaded by

Muhiuddin Arif
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Dynamic Programming 2

Uploaded by

Muhiuddin Arif
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

Solution:

def longestCommonSubsequence(text1: str, text2: str) -> int:


m, n = len(text1), len(text2)
dp = [[0] * (n + 1) for _ in range(m + 1)]

for i in range(1, m + 1):


for j in range(1, n + 1):
if text1[i - 1] == text2[j - 1]:
dp[i][j] = dp[i - 1][j - 1] + 1
else:
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])

return dp[m][n]

Time Complexity:

● O(m * n), where m is the length of text1 and n is the length of text2. We fill up a 2D
table of size (m+1) x (n+1) with each cell being filled in constant time.
Space Complexity:

● O(m * n). We use a 2D array of size (m+1) x (n+1) to store the intermediate results.

Solution:
def lengthOfLIS(nums):
if not nums:
return 0

n = len(nums)
dp = [1] * n

for i in range(1, n):


for j in range(i):
if nums[i] > nums[j]:
dp[i] = max(dp[i], dp[j] + 1)

return max(dp)

Time Complexity:

● O(n^2) where n is the length of the array nums. This is because for each element i, we
iterate over all previous elements j (where j < i).

Space Complexity:

● O(n) because we use an array dp of size n to store the results

You might also like