> For the complete documentation index, see [llms.txt](https://gl01.gitbook.io/gfg-editorials/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://gl01.gitbook.io/gfg-editorials/2023/12-2023-dec-16/17-max-sum-without-adjacents.md).

# 17. Max Sum without Adjacents

The problem can be found at the following link: [Question Link](https://www.geeksforgeeks.org/problems/max-sum-without-adjacents2430/1)

![](https://badgen.net/badge/Level/Easy/green)

## My Approach

To find the maximum sum of elements in an array for this question, I use a dynamic programming approach. The idea is to maintain two variables, `lastPrev` and `prev`, representing the maximum sums excluding and including the last element, respectively. I iterate through the array, updating these variables at each step to consider the current element or skip it.

## Time and Auxiliary Space Complexity

* **Time Complexity**: `O(n)`, where n is the size of the array.
* **Auxiliary Space Complexity**: `O(1)`, as I only use a constant amount of extra space.

## Code (C++)

```cpp
class Solution {
public:
    int findMaxSum(int *arr, int n) {
        int lastPrev = 0;
        int prev = arr[0];
        int curr = 0;

        for (int i = 1; i < n; ++i) {
            curr = max(prev, arr[i] + lastPrev);
            lastPrev = prev;
            prev = curr;
        }

        return max(lastPrev, prev);
    }
};
```

## Contribution and Support

For discussions, questions, or doubts related to this solution, please visit our [discussion section](https://github.com/getlost01/gfg-potd/discussions). We welcome your input and aim to foster a collaborative learning environment.

If you find this solution helpful, consider supporting us by giving a `⭐ star` to the [getlost01/gfg-potd](https://github.com/getlost01/gfg-potd) repository.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://gl01.gitbook.io/gfg-editorials/2023/12-2023-dec-16/17-max-sum-without-adjacents.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
