imashutosh51

Maximum sum such that no two elements are adjacent

Nov 3rd, 2022 (edited)
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.65 KB | None | 0 0
  1. /*
  2. Method 1:
  3. There is only two possibilties:
  4. Either take the elment of don't take the element.
  5. using a 1-D dp table to store the maximum till the ith house.
  6. T.C : O(n), S.C : O(n)
  7. */
  8.  
  9. /*
  10. class Solution{
  11.    public:
  12.    int FindMaxSum(int arr[], int n){
  13.        int dp[n];
  14.        dp[0]=arr[0];
  15.        dp[1]=max(arr[0],arr[1]);
  16.        for(int i=2;i<n;i++){
  17.            dp[i]=max(dp[i-1],dp[i-2]+arr[i]);
  18.        }
  19.        return dp[n-1];
  20.    }
  21. };
  22. */
  23. //We need only two prev value.
  24. def rob(nums):
  25.    prev2, prev1 = 0, 0
  26.    for num in nums:
  27.        prev2, prev1 = prev1, max(prev1, prev2 + num)
  28.    return prev1
  29.        
  30.  
  31.        
Advertisement
Add Comment
Please, Sign In to add comment