- Related Questions & Answers
- Maximum sum such that no two elements are adjacent in C++
- Maximum sum in a 2 x n grid such that no two elements are adjacent in C++
- Maximum sum in circular array such that no two elements are adjacent in C++
- Maximum subsequence sum such that no three are consecutive
- Maximum set bit sum in array without considering adjacent elements in C++
- Maximum sum of difference of adjacent elements in C++
- Ways to paint stairs with two colors such that two adjacent are not yellow in C++
- Pick maximum sum M elements such that contiguous repetitions do not exceed K in C++
- Maximum value K such that array has at-least K elements that are >= K in C++
- Print n 0s and m 1s such that no two 0s and no three 1s are together in C Program
- Maximum sum from three arrays such that picking elements consecutively from same is not allowed in C++
- Maximum Subarray Sum after inverting at most two elements in C++
- Place N^2 numbers in matrix such that every row has an equal sum in C++
- Maximum subarray size, such that all subarrays of that size have sum less than k in C++
- Find a triplet such that sum of two equals to third element in C++

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

In this tutorial, we will be discussing a program to find maximum sum such that no two elements are adjacent.

For this we will be provided with an array containing positive integers. Our task is to find the maximum sum subsequence such that they don’t have any two elements adjacent to each other.

#include <bits/stdc++.h> #define maxLen 10 using namespace std; int dp[maxLen]; bool v[maxLen]; //calculating the maximum subsequence int maxSum(int arr[], int i, int n) { if (i >= n) return 0; if (v[i]) return dp[i]; v[i] = 1; dp[i] = max(maxSum(arr, i + 1, n), arr[i] + maxSum(arr, i + 2, n)); return dp[i]; } int main() { int arr[] = { 12, 9, 7, 33 }; int n = sizeof(arr) / sizeof(int); cout << maxSum(arr, 0, n); return 0; }

45

Advertisements