Scrivio Interview library
Dynamic programmingDynamic programmingReported 26 times · 16 min read · updated 14 November 2026

Find the largest sum of array elements such that no two chosen elements are adjacent.

1What the question asks, told with coins on a table

Imagine a row of coins on a table, each with a value written on it. You may take as many coins as you like, but there is one rule: you may never take two coins that touch, and in a row each coin touches only its neighbours on either side. You want to walk away with the largest total. That is the whole problem. The coins are the array elements, touching means adjacent, which is the word for next to each other, and the total is the sum we must make as large as possible.

Let us use the coins 2, 7, 9, 3 and 1 for the whole article. The answer is 12, from taking 2, 9 and 1, the coins at positions 0, 2 and 4. Notice what this example already teaches. The biggest coin, 9, is in the answer, but the second biggest, 7, is not, because it touches 9. And the answer takes three small and medium coins rather than two larger ones.

PictureThe five coins and the best choice

Each cell is a coin and its value. The highlighted coins are the best choice in which no two chosen coins touch.

  1. 2071923314
    chosen
    2, 9, 1
    best sum
    12
    7 + 3
    10, not enough

    1Taking the coins at positions 0, 2 and 4 gives 2 + 9 + 1 = 12, and no two of them touch. No other allowed choice does better.

What to assume

Can the values be negative?
We assume yes.
May we take nothing at all?
We assume yes, so the answer is never below 0, and [-1, -4] gives 0.
Can the array be empty?
Yes, and then the answer is 0.
How large can the sums get?
Large, so we return a long, a 64-bit number that does not overflow as early as an int.

Let us check a few choices by hand to get a feel for it. 7 and 3 touch nothing, but give only 10. 2 and 9 give 11, and adding 1, which does not touch 9, gives 12. 7 and 1 give 8. We cannot take 7 and 9 together, because they touch. After a few minutes of this, a beginner usually suspects that 12 is the best, but has no way to be sure. That uncertainty is exactly what the method in this article removes.

A careful candidate asks a few questions first. Can the values be negative? We assume yes. May we take nothing at all? We assume yes, so the answer is never below 0, and [-1, -4] gives 0. Can the array be empty? Yes, and then the answer is 0. How large can the sums get? Large, so we return a long, a 64-bit number that does not overflow as early as an int.

2How to spot that this is dynamic programming

When a beginner first meets this question, the usual plan is to grab the biggest coins first. Take 9, which blocks 7 and 3, then take what is left. On our coins that happens to give 9 + 2 + 1 = 12. But we will see in the next section that this plan fails on a row of just three coins, and once a plan fails on three coins, we cannot trust it on three thousand.

So let us read the question slowly and take its clues one at a time. The first clue is that every element faces a yes or no decision: take it or leave it. Problems made of many small decisions, one per element, are the ground where dynamic programming grows.

The second clue is the rule no two chosen elements are adjacent. It ties each decision to the one just before it. Whether we may take coin 3 depends on whether we took coin 2, and on nothing further back. A rule that looks only at the previous decision means we will not need to remember the whole history, only a little about the last step.

The third clue is the word largest. We are not asked to list the allowed choices, only to find the best total. When we need only the best value, we can throw away every worse way of reaching the same point, and keep a single number for each situation.

Together these clues point to dynamic programming. The name sounds grand, but the idea is plain: solve the problem for a small piece of the input, then use that answer to solve a slightly bigger piece, and write each answer down so that it is never worked out twice. Here the pieces are prefixes, the first one coin, the first two coins, and so on. The general rule to carry to new problems is this: a choice at each element, a rule linking neighbouring choices, and a best total to find, together suggest dynamic programming over prefixes.

Some patterns look similar but do not fit. A greedy method, always taking the choice that looks best right now, is the closest, and it fails, as we will see. Backtracking, which tries every allowed set of coins one by one, finds the answer but takes exponential time. A sliding window, a frame moved along the array, needs the chosen elements to sit side by side, which is the very thing this problem forbids.

3The honest first attempt, trying every choice

Before the honest brute force, let us look at the mistake that tempts almost everyone, because it shows why we need care. Take the biggest coin, block its neighbours, and repeat. On the row 2, 3, 2 this takes 3 and blocks both 2s, ending with 3, while 2 + 2 = 4 is better. Another tempting rule is to take every other coin, either all the even positions or all the odd ones. On 5, 1, 1, 5 the even positions give 6 and the odd positions give 6, while 5 + 5 = 10 is better, by skipping two coins in a row. A rule that only looks at the current coin cannot see these trades.

So the honest first attempt tries every allowed choice. Stand at coin i and ask: what is the best total I can still collect from here to the end? There are only two things to do with coin i. Leave it, and the answer is the best from coin i + 1. Or take it, and then coin i + 1 is off limits, so the answer is a[i] plus the best from coin i + 2. We take the larger of the two. When i runs past the last coin there is nothing left, and the best is 0.

Step throughThe brute force asks the same question again and again

f(i) means the best total from coin i to the end. Each call has a left child for skipping coin i and a right child for taking it. Only the top four levels of the 25 calls are drawn.

  1. f(0)f(1)f(2)f(2)f(3)f(3)f(4)f(3)f(4)f(4)f(5)f(4)f(5)f(5)f(6)
    calls in all
    25
    coins
    5

    1f(0) asks two questions: the best from coin 1 if we skip coin 0, and the best from coin 2 if we take it. Each of those asks two more.

  2. f(0)f(1)f(2)f(2)f(3)f(3)f(4)f(3)f(4)f(4)f(5)f(4)f(5)f(5)f(6)
    f(2) computed
    2 times

    2f(2), the best from coin 2 onwards, is worked out twice from scratch, once after skipping 0 and 1 and once after taking 0.

  3. f(0)f(1)f(2)f(2)f(3)f(3)f(4)f(3)f(4)f(4)f(5)f(4)f(5)f(5)f(6)
    f(3) computed
    3 times
    f(4) computed
    5 times

    3f(3) appears three times in just these four levels, and f(4) is computed 5 times in the full run. The same answers are rebuilt over and over.

Java
// The best total we can still collect from index i to the end.
static long best(int[] a, int i) {
if (i >= a.length) return 0; // no coins left: nothing to add
long skipIt = best(a, i + 1); // leave a[i] on the table
long takeIt = a[i] + best(a, i + 2); // take a[i], so a[i + 1] is off limits
return Math.max(skipIt, takeIt);
}

Let us call the method f(i) for short, the best total from coin i onwards. Our answer is f(0). By hand, f(4) is the last coin alone, max(0, 1) = 1, and f(3) is max(f(4), 3 + f(5)) = max(1, 3) = 3. Then f(2) = max(f(3), 9 + f(4)) = max(3, 10) = 10, and in the same way f(1) = max(10, 7 + 3) = 10 and f(0) = max(10, 2 + 10) = 12. It works, and the recursion is a faithful copy of the take or leave choice.

Now let us count its work. Our traced run makes 25 calls for 5 coins. For 10 coins it makes 287 calls, for 20 coins 35,421, and for 30 coins more than four million. Each extra coin multiplies the work by about 1.6, so the time grows exponentially, roughly 1.6 to the power n. The space is only O(n), for the chain of waiting calls.

Where does all that work go? The picture shows the top of the call tree. f(2) is worked out twice, f(3) three times, f(4) five times. Each time, the answer is the same, because the best total from coin 3 onwards does not care how we got to coin 3. The brute force keeps asking questions it has already answered.

4From repeated questions to two running totals

The waste tells us exactly what to do, which is to work each answer out once and remember it. We could keep the recursion and store each f(i) in an array the first time we compute it, which is called memoization. That alone brings the time down to O(n). But we can go further, and the final method becomes simpler than the recursion.

Let us turn the direction around and walk the coins from left to right, the way we would at a real table. As we reach each coin, we keep two numbers. take is the best total so far if we take the current coin. skip is the best total so far if we leave it. Two numbers are enough because of the second clue: the only thing the next coin needs to know is whether this coin was taken.

Now the question a beginner asks at the hard step. How do we update take and skip for a new coin x? Let us reason it out slowly. If we take x, the coin before it must have been left, so the new take is the old skip plus x. If we leave x, the coin before it may have been taken or left, whichever was better, so the new skip is the larger of the old take and the old skip. Those two lines are the whole method.

Here is the trap in those two lines. If we write take = skip + x first, and then skip = max(skip, take), the second line sees the new take, which already includes x. The new skip would then count x as well, and the method could take two touching coins. Both new values must be computed from the old pair, so the code first stores them in newTake and newSkip and only then copies them in.

Why is it correct? After each coin, take really is the best total for that prefix with its last coin taken, and skip the best with it left. At the start both are 0, which is true for an empty prefix. Each update looks at every legal way to extend the two best plans, and a worse plan for the same prefix can never become better later, because later coins treat both the same. So after the last coin, the answer is the larger of take and skip.

If you have seen this problem written as best[i] = max(best[i - 1], best[i - 2] + a[i]), it is the same idea. best[i - 1] is the larger of take and skip before coin i, and best[i - 2] is the skip value. Keeping only two numbers is the table with everything but the last two entries thrown away.

5Watching take and skip move along the five coins

The picture runs the method on 2, 7, 9, 3, 1. In each frame the current coin is highlighted, and the panel shows take and skip after that coin, along with the plan behind each total, the coins it uses. The plans are not stored by the real code; they are shown only so you can see why each number is what it is.

Step throughTwo running totals walk along 2, 7, 9, 3, 1

take is the best total if the current coin is taken, skip the best if it is left. The plans show which coins each total uses.

  1. 2071923314
    take
    0
    skip
    0

    1Before any coin, both totals are 0: we have taken nothing, and so far there is nothing we could have taken.

  2. 2071923314i
    coin
    2
    take
    2
    skip
    0
    take plan
    2
    skip plan
    nothing

    2Coin 2. To take it, we add it to skip, which is 0, so take = 2. To leave it, skip = max(0, 0) = 0, the best total from before.

  3. 2071923314i
    coin
    7
    take
    7
    skip
    2
    take plan
    7
    skip plan
    2

    3Coin 7. Taking it needs the previous coin left, so take = old skip + 7 = 0 + 7 = 7. Leaving it keeps the better old total, skip = max(0, 2) = 2.

  4. 2071923314i
    coin
    9
    take
    11
    skip
    7
    take plan
    2 + 9
    skip plan
    7

    4Coin 9. take = old skip + 9 = 2 + 9 = 11, the plan 2 and 9. skip = max(2, 7) = 7, the plan that took 7.

  5. 2071923314i
    coin
    3
    take
    10
    skip
    11
    take plan
    7 + 3
    skip plan
    2 + 9

    5Coin 3. take = old skip + 3 = 7 + 3 = 10, the plan 7 and 3. skip = max(7, 11) = 11, so leaving 3 keeps the plan 2 and 9.

  6. 2071923314i
    coin
    1
    take
    12
    skip
    11
    take plan
    2 + 9 + 1
    skip plan
    2 + 9

    6Coin 1. take = old skip + 1 = 11 + 1 = 12, the plan 2, 9 and 1. skip = max(11, 10) = 11.

  7. 2071923314
    take
    12
    skip
    11
    answer
    12

    7The coins are used up. The answer is the larger of take and skip, max(12, 11) = 12, from coins 2, 9 and 1.

Let us read the important frames back. At coin 9, take becomes 2 + 9 = 11, because the best plan that left 7 was the plan that took 2. This is the moment the method finds the trade that greed cannot see: giving up 7 to make room for 9.

At coin 3 something subtle happens. take is only 7 + 3 = 10, but skip jumps to 11, by leaving 3 and keeping 2 and 9. So the best plan so far now leaves the current coin, which is perfectly allowed. At coin 1, take adds 1 to that 11, giving 12.

Check the last frame yourself. The answer is max(12, 11) = 12, the plan 2, 9 and 1. Five coins took five updates, two short lines each, instead of 25 calls.

6The complete Java program

Here is the whole program. The method maxNonAdjacent keeps the two totals, and main runs our coins, the row where the best choice skips two coins in a row, a mixed example, an all negative array and an empty one, each with its printed result as a comment.

Java
public class NonAdjacentSum {
// Largest sum of elements with no two chosen elements next to each other.
// Choosing nothing is allowed, so the answer is never below 0.
static long maxNonAdjacent(int[] a) {
long skip = 0; // best total so far when the previous element is NOT chosen
long take = 0; // best total so far when the previous element IS chosen
for (int x : a) {
long newTake = skip + x; // take x: the previous one must be skipped
long newSkip = Math.max(skip, take); // skip x: the previous one may be either
take = newTake;
skip = newSkip;
}
return Math.max(skip, take);
}
public static void main(String[] args) {
System.out.println(maxNonAdjacent(new int[] {2, 7, 9, 3, 1})); // 12
System.out.println(maxNonAdjacent(new int[] {5, 1, 1, 5})); // 10
System.out.println(maxNonAdjacent(new int[] {3, 2, 7, 10})); // 13
System.out.println(maxNonAdjacent(new int[] {-1, -4})); // 0
System.out.println(maxNonAdjacent(new int[] {})); // 0
}
}

Let us read it in the order it runs. skip and take both start at 0, because before the first coin nothing has been taken. They are longs so that a large array of large values cannot overflow.

The for loop visits each coin x once. newTake = skip + x is the take rule, built from the old skip. newSkip = Math.max(skip, take) is the leave rule, built from the old pair. Only after both are computed do we assign them, which avoids the trap of mixing old and new values.

After the loop, Math.max(skip, take) picks the better of the two endings. For 5, 1, 1, 5 this gives 10, from the two 5s with two coins skipped between them, which the every other coin rule missed. For 3, 2, 7, 10 it gives 13, from 3 and 10.

For the all negative array, take goes negative at each step, but skip never drops below 0, because it starts at 0 and only ever takes a maximum. So the answer is 0, which means take nothing, as we agreed. For the empty array the loop never runs and the answer is 0.

7How much it costs, and the cases at the edges

Let us count on the example first. Five coins needed five passes of the loop, each with one addition and one comparison. For n coins that is n passes, so the time is O(n), read as order n, meaning the work grows in step with the number of coins. Compare that with 25 calls for 5 coins and over four million for 30 in the brute force.

The extra space is O(1), a constant, because we keep two longs and two temporary values however long the array is. A table of size n, best[i], gives the same time with O(n) space, which is worth it only when we also need to recover which coins were chosen.

Comparing the ways to find the largest non-adjacent sum
ApproachTimeExtra space
Greedy: biggest coin firstO(n log n)O(n)
Try every choice by recursionabout 1.6 to the power nO(n) call stack
Recursion with memoizationO(n)O(n)
Two running totals, take and skipO(n)O(1)
The greedy row is fast but gives wrong answers, as on 2, 3, 2.

The edge cases need no special code. An empty array returns 0 because the loop never runs. A single coin returns its value, or 0 if it is negative. Two coins return the larger one, because they touch. An all negative array returns 0, because skip never falls below 0.

One case depends on the rules. If the interviewer says at least one coin must be chosen, an all negative array should return its largest element instead of 0. We check for that case first, by finding the maximum element, and return it when it is negative; otherwise we run the method as written.

8Follow-up questions

What if the elements are arranged in a circle, so the first and last are adjacent?

Then the first and last coins touch and cannot both be taken. The trick is to split the circle into two straight rows: one without the last coin, positions 0 to n - 2, and one without the first coin, positions 1 to n - 1. Any legal choice on the circle is a legal choice on one of those rows, so we run our method on both and return the larger answer. Each run is O(n), so the total stays O(n). A circle of one coin is the special case, where we return that coin.

How would you return the chosen elements, not just the sum?

We keep the full table best[i], the best total for the first i + 1 coins, and walk backwards from the last coin. If best[i] equals best[i - 1], coin i was not needed, so we step to i - 1. Otherwise coin i was taken, so we record it and jump to i - 2, because its neighbour cannot be in the plan. For our coins the table is 2, 7, 11, 11, 12, and the walk records 1, 9 and 2. It costs O(n) space for the table and O(n) time for the walk.

Why does the order of the two updates matter?

Both new values must be built from the old pair. If we wrote take = skip + x and then skip = max(skip, take), the second line would read the take we had just changed, which already includes x. The new skip could then contain x, and a later take would add the next coin to it, choosing two touching coins. Computing newTake and newSkip first, and assigning afterwards, keeps the old values intact while both rules read them.

9Conclusion

We found the largest non-adjacent sum by walking the array once with two totals: take, the old skip plus the current element, and skip, the better of the old pair, and the answer is the larger of the two at the end. It takes O(n) time and O(1) space, against roughly 1.6 to the power n for trying every choice. The clue to remember is a take or leave choice at every element, a rule that ties each choice to the one before it, and a best total to find; that combination points to dynamic programming over prefixes.

What to say in the interviewAbout 80 seconds aloud

Open with

Let me check the rules first: values may be negative, choosing nothing is allowed so the answer is at least zero, and I will return a long. A greedy rule such as taking the largest element first fails; on 2, 3, 2 it takes 3, while 2 plus 2 is 4.

Then, if they want more

Trying every choice recursively, where each element is either skipped or taken, is correct but exponential, because the same suffixes are solved again and again. So I will use dynamic programming. As I scan the array I keep two values: take, the best total if the current element is chosen, and skip, the best total if it is not.

For a new element x, taking it requires the previous element to be skipped, so the new take is the old skip plus x, and leaving it allows either, so the new skip is the maximum of the old take and the old skip. I compute both from the old values before assigning either, so I never count two neighbours.

At the end I return the larger of the two. On 2, 7, 9, 3, 1 that gives 12, from 2, 9 and 1. It is O(n) time and O(1) space, and an empty or all negative array returns zero.

About this answer

Last updated
14 November 2026
Written for
Java 21, using only java.util
Checked
The Java solution was compiled and run, and each printed result matches the comment beside it. The pictures are checked against the format when the site is built. The explanation around the code is a study note: confirm anything critical against the documentation below. What the checks cover
Where the question comes from
Public interview write-ups, reworded by Scrivio; counted 26 times in that collection. How it is counted
Official documentation
java.util, package documentation
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Find the largest sum of array elements such that no two chosen elements are adjacent.": https://scrivio-interview-library.netlify.app/data-structures/solutions/find-the-largest-sum-of-array-elements-such-that-no-two-chosen-e-4b5a51/