Open In App

Maximum sum such that no two elements are adjacent (Stickler Thief)

Improve
Improve
Like Article
Like
Save
Share
Report

Given an array arr[] of positive numbers, The task is to find the maximum sum of a subsequence such that no 2 numbers in the sequence should be adjacent in the array.

Examples: 

Input: arr[] = {5, 5, 10, 100, 10, 5}
Output: 110
Explanation: Pick the subsequence {5, 100, 5}.
The sum is 110 and no two elements are adjacent. This is the highest possible sum.

Input: arr[] = {3, 2, 7, 10}
Output: 13
Explanation: The subsequence is {3, 10}. This gives sum = 13.
This is the highest possible sum of a subsequence following the given criteria

Input: arr[] = {3, 2, 5, 10, 7}
Output: 15
Explanation: Pick the subsequence {3, 5, 7}. The sum is 15.

Naive Approach: Below is the idea to solve the problem:

Each element has two choices: either it can be the part of the subsequence with the highest sum or it cannot be part of the subsequence. So to solve the problem, build all the subsequences of the array and find the subsequence with the maximum sum such that no two adjacent elements are present in the subsequence.

  1. The robber has two options: to rob the current house (option “a”) or not to rob it (option “b”). 
  2. If the robber chooses option “a”, they cannot rob the previous house (i-1), but can proceed to the one before that (i-2) and receive all the accumulated loot.
  3. If option “b” is selected, the robber will receive all the potential loot from the previous house (i-1) and all the houses before it. 
  4. The decision of which option to choose ultimately comes down to determining which is more profitable: the loot obtained from the current house and previous houses before the one before the last, or the loot obtained from the previous house and all prior houses. 
  5. The formula used to make this calculation is: rob(i) = Math.max( rob(i – 2) + currentHouseValue, rob(i – 1) ).

C++




// C++ code to implement the approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the maximum sum
int rec(vector<int>& nums, int idx)
{
    if (idx >= nums.size())
        return 0;
    return max(nums[idx] + rec(nums, idx + 2),
               rec(nums, idx + 1));
}
 
int findMaxSum(vector<int> arr, int N)
{
    return rec(arr, 0);
}
 
// Driver Code
int main()
{
    // Creating the array
    vector<int> arr = { 5, 5, 10, 100, 10, 5 };
    int N = arr.size();
 
    // Function call
    cout << findMaxSum(arr, N) << endl;
    return 0;
}


C




// C code to implement the approach
 
#include <stdio.h>
 
// Function to find the maximum sum
int rec(int* nums, int idx, int size)
{
    if (idx >= size)
        return 0;
    return (nums[idx] + rec(nums, idx + 2, size)
            > rec(nums, idx + 1, size))
               ? nums[idx] + rec(nums, idx + 2, size)
               : rec(nums, idx + 1, size);
}
 
int findMaxSum(int* arr, int N) { return rec(arr, 0, N); }
 
// Driver Code
int main()
{
    // Creating the array
    int arr[] = { 5, 5, 10, 100, 10, 5 };
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function call
    printf("%d", findMaxSum(arr, N));
    return 0;
}


Java




/*package whatever //do not write package name here */
import java.util.*;
 
class GFG
{
  // Function to find the maximum sum
  static int rec(int nums[], int idx,int N)
  {
      if (idx >= N)
          return 0;
      return Math.max(nums[idx] + rec(nums, idx + 2, N),
                 rec(nums, idx + 1, N));
  }
   
  // Function to find the maximum sum
  static int findMaxSum(int[] arr, int N)
  {
      return rec(arr, 0, N);
  }
 
 
  // Driver Code
  public static void main(String args[])
  {
      // Creating the array
      int[] arr = { 5, 5, 10, 100, 10, 5 };
      int N = 6;
 
      // Function call
      System.out.println(findMaxSum(arr, N));
  }
}
 
// This code is contributed by shubhamrajput6156


Python3




# Function to find the maximum sum
def rec(nums, idx):
    if idx >= len(nums):
        return 0
    return max(nums[idx] + rec(nums, idx + 2), rec(nums, idx + 1))
 
def findMaxSum(arr, N):
    return rec(arr, 0)
 
# Driver Code
if __name__ == "__main__":
    # Creating the array
    arr = [5, 5, 10, 100, 10, 5]
    N = len(arr)
 
    # Function call
    print(findMaxSum(arr, N))


C#




// C# code to implement the approach
 
using System;
using System.Collections.Generic;
 
class Program
{
// Function to find the maximum sum
static int Rec(List<int> nums, int idx)
{
if (idx >= nums.Count)
return 0;
return Math.Max(nums[idx] + Rec(nums, idx + 2),
Rec(nums, idx + 1));
}
  static int FindMaxSum(List<int> arr, int N)
{
    return Rec(arr, 0);
}
 
static void Main(string[] args)
{
    // Creating the list
    List<int> arr = new List<int>() { 5, 5, 10, 100, 10, 5 };
    int N = arr.Count;
 
    // Function call
    Console.WriteLine(FindMaxSum(arr, N));
}
}
 
//This code is contributed by shivamsharma215


Javascript




// Javascript code to implement the approach
// Function to find the maximum sum
 
function rec(nums, idx)
{
    if (idx >= nums.length)
        return 0;
    return Math.max(nums[idx] + rec(nums, idx + 2), rec(nums, idx + 1));
}
 
function findMaxSum(arr, N)
{
    return rec(arr, 0);
}
 
// Driver Code
// Creating the array
arr = [5, 5, 10, 100, 10, 5];
N = arr.length;
 
// Function call
console.log(findMaxSum(arr, N));
 
// The code is contributed by Nidhi goel.


Output

110

Time Complexity: O(2N) where N is the number of elements in A. At each index, we have two choices of either robbing or not robbing the current house. Thus this leads to a time complexity of 222…n times ≈ O(2^N)
Auxiliary Space: O(N) It is recursive stack space.

Maximum sum such that no two elements are adjacent using Dynamic Programming (Memoization):

We can cache the overlapping subproblems

C++




// C++ code to implement the approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the maximum sum
 
int rec(vector<int>& nums, int idx, vector<int>& dp)
{
    if (idx >= nums.size())
        return 0;
    if (dp[idx] != -1)
        return dp[idx];
    return dp[idx]
           = max(rec(nums, idx + 1, dp),
                 nums[idx] + rec(nums, idx + 2, dp));
}
int findMaxSum(vector<int>& nums, int N)
{
    vector<int> dp(N + 1, -1);
    return rec(nums, 0, dp);
}
 
// Driver Code
int main()
{
    // Creating the array
    vector<int> arr = { 5, 5, 10, 100, 10, 5 };
    int N = arr.size();
 
    // Function call
    cout << findMaxSum(arr, N) << endl;
    return 0;
}


C




// C code to implement the approach
 
#include <stdio.h>
#include <stdlib.h>
 
// Function to find the maximum sum
int rec(int* nums, int idx, int* dp, int size)
{
    if (idx >= size)
        return 0;
    if (dp[idx] != -1)
        return dp[idx];
    return dp[idx]
           = (rec(nums, idx + 1, dp, size)
              > nums[idx] + rec(nums, idx + 2, dp, size))
                 ? rec(nums, idx + 1, dp, size)
                 : nums[idx] + rec(nums, idx + 2, dp, size);
}
 
int findMaxSum(int* nums, int N)
{
    int* dp = (int*)malloc((N + 1) * sizeof(int));
    for (int i = 0; i < N + 1; i++)
        dp[i] = -1;
    int result = rec(nums, 0, dp, N);
    free(dp);
    return result;
}
 
// Driver Code
int main()
{
    // Creating the array
    int arr[] = { 5, 5, 10, 100, 10, 5 };
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function call
    printf("%d\n", findMaxSum(arr, N));
    return 0;
}


Java




import java.util.*;
 
public class Main {
 
    // Function to find the maximum sum
    public static int rec(List<Integer> nums, int idx, int[] dp) {
        // base case: if the current index is out of bounds, return 0
        if (idx >= nums.size()) {
            return 0;
        }
         
        // if the result for the current index has already been computed, return it
        if (dp[idx] != -1) {
            return dp[idx];
        }
         
        // recursive case: compute the maximum sum by either skipping the current element or including it
        dp[idx] = Math.max(rec(nums, idx + 1, dp), nums.get(idx) + rec(nums, idx + 2, dp));
         
        return dp[idx];
    }
 
    public static int findMaxSum(List<Integer> nums, int N) {
        int[] dp = new int[N + 1];
        Arrays.fill(dp, -1);
        return rec(nums, 0, dp);
    }
 
    public static void main(String[] args) {
        // Creating the array
        List<Integer> arr = Arrays.asList(5, 5, 10, 100, 10, 5);
        int N = arr.size();
 
        // Function call
        System.out.println(findMaxSum(arr, N));
    }
}


Python3




def findMaxSum(nums, N):
    dp = [-1] * (N + 1)
 
    def rec(idx, dp):
        if idx >= len(nums):
            return 0
        if dp[idx] != -1:
            return dp[idx]
        dp[idx] = max(rec(idx + 1, dp), nums[idx] + rec(idx + 2, dp))
        return dp[idx]
 
    return rec(0, dp)
 
 
# Driver Code
arr = [5, 5, 10, 100, 10, 5]
N = len(arr)
 
print(findMaxSum(arr, N))


C#




using System;
using System.Collections.Generic;
 
class GFG
{
    // Function to find the maximum sum
    static int Rec(List<int> nums, int idx, List<int> dp)
    {
        if (idx >= nums.Count)
            return 0;
        if (dp[idx] != -1)
            return dp[idx];
        return dp[idx]
               = Math.Max(Rec(nums, idx + 1, dp),
                           nums[idx] + Rec(nums, idx + 2, dp));
    }
 
    static int FindMaxSum(List<int> nums, int N)
    {
        List<int> dp = new List<int>(N + 1);
        for (int i = 0; i <= N; i++)
        {
            dp.Add(-1);
        }
        return Rec(nums, 0, dp);
    }
 
    static void Main(string[] args)
    {
        // Creating the list
        List<int> arr = new List<int>() { 5, 5, 10, 100, 10, 5 };
        int N = arr.Count;
 
        // Function call
        Console.WriteLine(FindMaxSum(arr, N));
    }
}


Javascript




function findMaxSum(nums, N) {
  const dp = new Array(N + 1).fill(-1);
   
  function rec(idx, dp) {
    if (idx >= nums.length) {
      return 0;
    }
    if (dp[idx] !== -1) {
      return dp[idx];
    }
    dp[idx] = Math.max(rec(idx + 1, dp), nums[idx] + rec(idx + 2, dp));
    return dp[idx];
  }
   
  return rec(0, dp);
}
 
// Driver Code
const arr = [5, 5, 10, 100, 10, 5];
const N = arr.length;
 
console.log(findMaxSum(arr, N));


Output

110

Time complexity: O(N) (recursion)
Space complexity: O(N)+O(N), one is recursive stack space and another O(N) is for dp array.

Maximum sum such that no two elements are adjacent using Dynamic Programming:

  • As seen above, each element has two choices. If one element is picked then its neighbours cannot be picked. Otherwise, its neighbours may be picked or may not be. 
  • So the maximum sum till ith index has two possibilities: the subsequence includes arr[i] or it does not include arr[i].
  • If arr[i] is included then the maximum sum depends on the maximum subsequence sum till (i-1)th element excluding arr[i-1].
  • Otherwise, the maximum sum is the same as the maximum subsequence sum till (i-1) where arr[i-1] may be included or excluded.

So build a 2D dp[N][2] array where dp[i][0] stores maximum subsequence sum till ith index with arr[i] excluded and dp[i][1] stores the sum when arr[i] is included.
The values will be obtained by the following relations: dp[i][1] = dp[i-1][0] + arr[i] and dp[i][0] = max(dp[i-1][0], dp[i-1][1])

Follow the steps mentioned below to implement the above idea:

  • If the size of the array is 1, then the answer is arr[0].
  • Initialize the values of dp[0][0] = 0 and dp[0][1] = arr[0].
  • Iterate from i = 1 to N-1:
    • Fill the dp array as per the relation shown above.
  • Return the maximum between dp[N-1][1] and dp[N-1][0] as that will be the answer.

Below is the implementation of the above approach.

C++




// C++ code to implement the approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the maximum sum
int findMaxSum(vector<int> arr, int N)
{
    // Declare dp array
    int dp[N][2];
    if (N == 1) {
        return arr[0];
    }
   
    // Initialize the values in dp array
    dp[0][0] = 0;
    dp[0][1] = arr[0];
   
    // Loop to find the maximum possible sum
    for (int i = 1; i < N; i++) {
        dp[i][1] = dp[i - 1][0] + arr[i];
        dp[i][0] = max(dp[i - 1][1],
                       dp[i - 1][0]);
    }
   
    // Return the maximum sum
    return max(dp[N - 1][0], dp[N - 1][1]);
}
 
// Driver Code
int main()
{
    // Creating the array
    vector<int> arr = { 5, 5, 10, 100, 10, 5 };
    int N = arr.size();
 
    // Function call
    cout << findMaxSum(arr, N) << endl;
    return 0;
}


C




// C code to implement the approach
 
#include <stdio.h>
 
// Function to find the maximum sum
int findMaxSum(int arr[], int N)
{
    // Declare dp array
    int dp[N][2];
    if (N == 1) {
        return arr[0];
    }
 
    // Initialize the values in dp array
    dp[0][0] = 0;
    dp[0][1] = arr[0];
 
    // Loop to find the maximum possible sum
    for (int i = 1; i < N; i++) {
        dp[i][1] = dp[i - 1][0] + arr[i];
        dp[i][0] = (dp[i - 1][1] > dp[i - 1][0])
                       ? dp[i - 1][1]
                       : dp[i - 1][0];
    }
 
    // Return the maximum sum
    return (dp[N - 1][0] > dp[N - 1][1]) ? dp[N - 1][0]
                                         : dp[N - 1][1];
}
 
// Driver Code
int main()
{
    // Creating the array
    int arr[] = { 5, 5, 10, 100, 10, 5 };
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function call
    printf("%d\n", findMaxSum(arr, N));
    return 0;
}


Java




/*package whatever //do not write package name here */
import java.io.*;
 
class GFG
{
 
  // Function to find the maximum sum
  static int findMaxSum(int[] arr, int N)
  {
    // Declare dp array
    int[][] dp = new int[N][2];
    if (N == 1) {
      return arr[0];
    }
 
    // Initialize the values in dp array
    dp[0][0] = 0;
    dp[0][1] = arr[0];
 
    // Loop to find the maximum possible sum
    for (int i = 1; i < N; i++) {
      dp[i][1] = dp[i - 1][0] + arr[i];
      dp[i][0] = Math.max(dp[i - 1][1],
                          dp[i - 1][0]);
    }
 
    // Return the maximum sum
    return Math.max(dp[N - 1][0], dp[N - 1][1]);
  }
 
 
  // Driver Code
  public static void main(String args[])
  {
 
    // Creating the array
    int[] arr = { 5, 5, 10, 100, 10, 5 };
    int N = arr.length;
 
    // Function call
    System.out.println(findMaxSum(arr, N));
  }
}
 
// This code is contributed by shinjanpatra


Python3




# Python code to implement the approach
 
# Function to find the maximum sum
def findMaxSum(arr, N):
 
    # Declare dp array
    dp = [[0 for i in range(2)] for j in range(N)]
     
    if (N == 1):
        return arr[0]
   
    # Initialize the values in dp array
    dp[0][0] = 0
    dp[0][1] = arr[0]
   
    # Loop to find the maximum possible sum
    for i in range(1,N):
        dp[i][1] = dp[i - 1][0] + arr[i]
        dp[i][0] = max(dp[i - 1][1], dp[i - 1][0])
   
    # Return the maximum sum
    return max(dp[N - 1][0], dp[N - 1][1])
 
# Driver Code
 
# Creating the array
arr = [ 5, 5, 10, 100, 10, 5 ]
N = len(arr)
 
# Function call
print(findMaxSum(arr, N))
 
# This code is contributed by shinjanpatra


C#




// C# program for above approach
using System;
 
class GFG{
     
// Function to find the maximum sum
int findMaxSum(int[] arr,int n)
{
     
    // Declare dp array
    int [,] dp = new int [n,2];
    if (n == 1) {
        return arr[0];
    }
    
    // Initialize the values in dp array
    dp[0,0] = 0;
    dp[0,1] = arr[0];
    
    // Loop to find the maximum possible sum
    for (int i = 1; i < n; i++) {
        dp[i,1] = dp[i - 1,0] + arr[i];
        dp[i,0] = Math.Max(dp[i - 1,1],
                       dp[i - 1,0]);
    }
    
    // Return the maximum sum
    return Math.Max(dp[n - 1,0], dp[n - 1,1]);
}
 
// Driver code
static public void Main ()
{
    GFG small = new GFG();
    int[] arr = {5, 5, 10, 100, 10, 5};
    int n = arr.Length;
     
    // Function Call
    Console.WriteLine(small.findMaxSum(arr,n));
}
}
 
// This code is contributed by Aarti_Rathi


Javascript




<script>
 
// JavaScript code to implement the approach
 
// Function to find the maximum sum
function findMaxSum(arr, N)
{
 
    // Declare dp array
    let dp = new Array(N);
    for(let i = 0; i < N; i++)
    {
        dp[i] = new Array(2);
    }
    if (N == 1)
    {
        return arr[0];
    }
   
    // Initialize the values in dp array
    dp[0][0] = 0;
    dp[0][1] = arr[0];
   
    // Loop to find the maximum possible sum
    for (let i = 1; i < N; i++) {
        dp[i][1] = dp[i - 1][0] + arr[i];
        dp[i][0] = Math.max(dp[i - 1][1],
                       dp[i - 1][0]);
    }
   
    // Return the maximum sum
    return Math.max(dp[N - 1][0], dp[N - 1][1]);
}
 
// Driver Code
 
// Creating the array
let arr = [ 5, 5, 10, 100, 10, 5 ];
let N = arr.length;
 
// Function call
document.write(findMaxSum(arr, N),"</br>");
 
/*This code is contribute by shinjanpatra */
 
</script>


Output

110

Time Complexity: O(N)
Auxiliary Space: O(N)

Space Optimized Approach: The above approach can be optimized to be done in constant space based on the following observation:

As seen from the previous dynamic programming approach, the value of current states (for ith element) depends upon only two states of the previous element. So instead of creating a 2D array, we can use only two variables to store the two states of the previous element.

  • Say excl stores the value of the maximum subsequence sum till i-1 when arr[i-1] is excluded and 
  • incl stores the value of the maximum subsequence sum till i-1 when arr[i-1] is included.
  • The value of excl for the current state( say excl_new) will be max(excl ,incl). And the value of incl will be updated to excl + arr[i].

Illustration:

Consider arr[] = {5,  5, 10, 100, 10, 5}

Initially at i = 0:  incl = 5, excl = 0

For i = 1: arr[i] = 5
        => excl_new = 5
        => incl = (excl + arr[i]) = 5
        => excl = excl_new = 5

For i = 2: arr[i] = 10
        => excl_new =  max(excl, incl) = 5
        => incl =  (excl + arr[i]) = 15
        => excl = excl_new = 5

For i = 3: arr[i] = 100
        => excl_new =  max(excl, incl) = 15
        => incl =  (excl + arr[i]) = 105
        => excl = excl_new = 15

For i = 4: arr[i] = 10
        => excl_new =  max(excl, incl) = 105
        => incl =  (excl + arr[i]) = 25
        => excl = excl_new = 105

For i = 5: arr[i] = 5
        => excl_new =  max(excl, incl) = 105
        => incl =  (excl + arr[i]) = 110
        => excl = excl_new = 105

So, answer is max(incl, excl) =  110

Follow the steps mentioned below to implement the above approach:

  • Initialize incl and excl with arr[0] and 0 respectively.
  • Iterate from i = 1 to N-1:
    • Update the values of incl and excl as mentioned above.
  • Return the maximum of incl and excl after the iteration is over as the answer.

Below is the implementation of the above approach.

C++




// C++ code to implement the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to return max sum such that
// no two elements are adjacent
int FindMaxSum(vector<int> arr, int n)
{
    int incl = arr[0];
    int excl = 0;
    int excl_new;
    int i;
 
    for (i = 1; i < n; i++) {
        // Current max excluding i
        excl_new = max(incl, excl);
 
        // Current max including i
        incl = excl + arr[i];
        excl = excl_new;
    }
 
    // Return max of incl and excl
    return max(incl, excl);
}
 
// Driver code
int main()
{
    vector<int> arr = { 5, 5, 10, 100, 10, 5 };
    int N = arr.size();
 
    // Function call
    cout << FindMaxSum(arr, N);
    return 0;
}
// This approach is contributed by Debanjan


C




// C code to implement the approach
 
#include <stdio.h>
 
// Function to return max sum such that
// no two elements are adjacent
int findMaxSum(int arr[], int n)
{
    int incl = arr[0];
    int excl = 0;
    int excl_new;
    int i;
 
    for (i = 1; i < n; i++) {
         
        // Current max excluding i
        excl_new = (incl > excl) ? incl : excl;
 
        // Current max including i
        incl = excl + arr[i];
        excl = excl_new;
    }
 
    // Return max of incl and excl
    return ((incl > excl) ? incl : excl);
}
 
// Driver code
int main()
{
    int arr[] = { 5, 5, 10, 100, 10, 5 };
    int N = sizeof(arr) / sizeof(arr[0]);
     
    // Function call
    printf("%d", findMaxSum(arr, N));
    return 0;
}


Java




// Java code to implement the approach
 
import java.lang.*;
import java.util.*;
 
class MaximumSum {
    // Function to return max sum such that
    // no two elements are adjacent
    int findMaxSum(int arr[], int n)
    {
        int incl = arr[0];
        int excl = 0;
        int excl_new;
        int i;
 
        for (i = 1; i < n; i++) {
            // Current max excluding i
            excl_new = Math.max(incl, excl);
 
            // Current max including i
            incl = excl + arr[i];
            excl = excl_new;
        }
 
        // Return max of incl and excl
        return Math.max(incl, excl);
    }
 
    // Driver code
    public static void main(String[] args)
    {
        MaximumSum sum = new MaximumSum();
        int arr[] = new int[] { 5, 5, 10, 100,
                                10, 5 };
        int N = arr.length;
 
        // Function call
        System.out.println(
            sum.findMaxSum(arr, arr.length));
    }
}
 
// This code has been contributed by Mayank Jaiswal


Python3




# Python code to implement the approach
 
# Function to return max sum such that
# no two elements are adjacent
def findMaxSum(arr, n):
    incl = 0
    excl = 0  
    for i in arr:
         
        # Current max excluding i
        new_excl = max (excl, incl)
         
        # Current max including i
        incl = excl + i
        excl = new_excl
     
    # Return max of incl and excl
    return max(excl, incl)
 
# Driver code
if __name__ == "__main__":
    arr = [5, 5, 10, 100, 10, 5]
    N = 6
     
    # Function call
    print (findMaxSum(arr, N))
 
# This code is contributed by Kalai Selvan


C#




// C# code to implement the approach
 
using System;
 
class GFG {   
    // Function to return max sum such
    // that no two elements are adjacent
    static int findMaxSum(int []arr, int n)
    {
        int incl = arr[0];
        int excl = 0;
        int excl_new;
        int i;
 
        for (i = 1; i < n; i++) {
            // Current max excluding i
            excl_new = (incl > excl) ?
                            incl : excl;
 
            // Current max including i
            incl = excl + arr[i];
            excl = excl_new;
        }
 
        // Return max of incl and excl
        return ((incl > excl) ?
                            incl : excl);
    }
 
    // Driver code
    public static void Main()
    {
        int []arr = new int[]{5, 5, 10,
                              100, 10, 5};
        int N = arr.Length;
 
        // Function call
        Console.Write(findMaxSum(arr, N));
    }
}
 
// This code has been contributed by
// nitin mittal


Javascript




<script>
 
// Javascript program for the above approach
 
// Function to return max sum such that
// no two elements are adjacent
function FindMaxSum(arr, n)
{
    let incl = arr[0];
    let excl = 0;
    let excl_new;
    let i;
 
    for(i = 1; i < n; i++)
    {
         
        // Current max excluding i
        excl_new = (incl > excl) ? incl : excl;
 
        // Current max including i
        incl = excl + arr[i];
        excl = excl_new;
    }
 
    // Return max of incl and excl
    return ((incl > excl) ? incl : excl);
}
 
// Driver code
let arr = [ 5, 5, 10, 100, 10, 5 ];
 
document.write(FindMaxSum(arr, arr.length));
 
// This code is contributed by Mayank Tyagi
 
</script>


PHP




<?php
// PHP code to find Maximum sum
// such that no two elements
// are adjacent
 
/* Function to return max sum
   such that no two elements
   are adjacent */
function FindMaxSum($arr, $n)
{
    $incl = $arr[0];
    $excl = 0;
    $excl_new;
    $i;
 
for ($i = 1; $i <$n; $i++)
{
     
    // current max excluding i
    $excl_new = ($incl > $excl)? $incl: $excl;
 
    // current max including i
    $incl = $excl + $arr[$i];
    $excl = $excl_new;
}
 
// return max of incl and excl
return (($incl > $excl)? $incl : $excl);
}
 
// Driver Code
$arr = array(5, 5, 10, 100, 10, 5);
$n = sizeof($arr);
echo FindMaxSum($arr, $n);
     
// This code is contributed by Ajit
?>


Output

110

Time Complexity: O(N)
Auxiliary Space: O(1).

Similar problem: Find maximum possible stolen value from houses
Please write comments if you find any bug in the above program/algorithm or other ways to solve the same problem.



Last Updated : 14 Sep, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads