imashutosh51

Max Sum Increasing Subsequence

Mar 20th, 2026
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.46 KB | None | 0 0
  1. """
  2. Intuition:
  3. The problem is similar to Longest Increasing Subsequence (LIS), but instead of
  4. maximizing the length, we maximize the sum of the subsequence.
  5.  
  6. At every index i, we ask:
  7. "What is the maximum sum of an increasing subsequence that MUST end at index i?"
  8.  
  9. To answer this, we look at all previous indices j < i:
  10. - If arr[j] < arr[i], then arr[i] can extend the subsequence ending at j
  11. - So we try: dp[j] + arr[i]
  12. - We take the maximum among all such valid j
  13.  
  14. If no such j exists, then the subsequence contains only arr[i].
  15.  
  16. Solution Intuition:
  17. - Define dp[i] = maximum sum of increasing subsequence ending at index i
  18. - Initialize dp[i] = arr[i] (every element alone is a valid subsequence)
  19. - For each i, iterate over all j < i:
  20.    if arr[j] < arr[i]:
  21.        dp[i] = max(dp[i], dp[j] + arr[i])
  22. - Final answer is max(dp), since subsequence can end anywhere
  23.  
  24. Time Complexity: O(n^2)
  25. Space Complexity: O(n)
  26. """
  27.  
  28. def fun(arr, i, dp):
  29.     if dp[i] != -1:
  30.         return dp[i]
  31.    
  32.     # Base: subsequence with only arr[i]
  33.     dp[i] = arr[i]
  34.    
  35.     # Try extending previous subsequences
  36.     for j in range(i):
  37.         if arr[j] < arr[i]:
  38.             dp[i] = max(dp[i], fun(arr, j, dp) + arr[i])
  39.    
  40.     return dp[i]
  41.  
  42.  
  43. class Solution:
  44.     def maxSumIS(self, arr):
  45.         n = len(arr)
  46.        
  47.         dp = [-1] * n
  48.        
  49.         ans = 0
  50.         for i in range(n):
  51.             ans = max(ans, fun(arr, i, dp))
  52.        
  53.         return ans
Advertisement
Add Comment
Please, Sign In to add comment