Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

Stickler Thief or Maximum sum such that no two elements are adjacent

Recursion :
def FindMaxSum(arr, n):
        
    def recur(arr, n):
        
        if n == 1:
            return arr[n-1]
        
        if n == 2:
            return max(arr[n-1], arr[n-2])
        
        return max(recur(arr, n-1), recur(arr, n-2) + arr[n-1])
    
    return recur(arr, n)
 
Top Down :
def FindMaxSum(arr, n):
        
    def top_down(arr, n, dp):
        
        if dp[n] != -1:
            return dp[n]
    
        dp[n] =  max(top_down(arr, n-1, dp), top_down(arr, n-2, dp) + arr[n-1])
        
        return dp[n]
    
    if n == 1:
        return arr[0]
    if n == 2:
        return max(arr[0], arr[1])
        
    dp =[-1 for i in range(n+1)]
    dp[1] = arr[0]
    dp[2] = max(arr[0], arr[1])
    
    return top_down(arr, n, dp)
  
Bottom Up :
def FindMaxSum(arr, n):
        
    def bottom_up(arr, n, dp):
        
        for i in range(2, n):
            dp[i] =  max(dp[i-1], dp[i-2] + arr[i])

    if n == 1:
        return arr[0]
    if n == 2:
        return max(arr[0], arr[1])
        
    dp =[0 for i in range(n)]
    dp[0] = arr[0]
    dp[1] = max(arr[0], arr[1])
    
    bottom_up(arr, n, dp)
    
    return dp[n-1]
Comment

PREVIOUS NEXT
Code Example
Python :: port python script to jupyter notebook 
Python :: custom auth django channels 
Python :: how to catch stop itteration in generator as None 
Python :: python compiler and shell online 
Python :: view back of list in python 
Python :: Python downsampling 
Python :: program to draw rectangle in python 
Python :: Python - Cara Bermain Mp3 File 
Python :: add hours to date time in python 
Python :: Type conversions in python 
Python :: aritmetics to a value in a dict python 
Python :: flask files not updating 
Python :: how to use python-socker.io with fast api 
Python :: fast guess for divisible numbers between two numbers 
Python :: Create tiff stack in python 
Python :: pandas : stratification (mean) 
Python :: asyncio RuntimeError: Event loop is closed 
Python :: Python Print Variable Using the String Formatting with the help of % character 
Python :: starter is a naive datetime. Use pytz to make it a "US/Pacific" datetime instead and assign this converted datetime to the variable local. 
Python :: argmax change dafault value for multiple maxima 
Python :: iris data pandas scatterplot 
Python :: python counter infinite series 
Python :: python range function 
Python :: get length of a tuple in python 
Python :: python lane angle detection 
Python :: pd assign index from different df 
Python :: python numpy bbox 
Python :: pyspark pivot max aggregation 
Python :: import cv2 illegal instruction (core dumped) 
Python :: loading model 
ADD CONTENT
Topic
Content
Source link
Name
6+6 =