Quick revision
The short answer
This is a dynamic programming problem in the Kadane family. We scan once and keep two values for the runs that end at the current index, the largest product and the smallest, because a negative number turns the smallest into the largest; when the current element is negative we swap the two before extending them. That is O(n) time and O(1) space.
The solution
What it costs
| Approach | Time | Space | Correct? |
|---|---|---|---|
| Brute force over every run | O(n^2) | O(1) | yes |
| Copy of the sum idea, best product only | O(n) | O(1) | no, misses sign flips |
| Largest and smallest product ending here | O(n) | O(1) | yes |
What to remember
We found the largest product of a contiguous run by keeping, for each index, both the largest and the smallest product of a run ending there, because a negative card turns the smallest into the largest. Swapping the two on a negative card, and letting each restart at the card alone, handles sign flips and zeros in one pass, with O(n) time and O(1) space. We start from a[0] so a single negative card is right, and we switch to long when products may grow large. The clue to remember is a best contiguous run built by extend or restart at each index: that is dynamic programming, and a sign flip means we must carry the minimum too.
1What the question asks, told as a game of multiplier cards
Imagine a card game. A row of cards lies face up on the table, each with a number on it, and you may pick up any run of neighbouring cards. Your score is all the numbers on your cards multiplied together. A 3 triples your score and a 0 wipes it out. A negative card is the strange one: it turns your score upside down, so a big win becomes a big loss, and a big loss becomes a big win. Our problem asks for the best score this game allows.
In programming words, a contiguous subarray is a run of neighbouring elements, such as a[2], a[3], a[4], written a[2..4]. We must find the largest product any such run can have. The run must hold at least one element, and we return the product, not the run itself.
We will use one example all the way through, the cards [2, -5, -2, -4, 3]. Let us try some runs by hand. [2] gives 2. [2, -5] gives -10, a bad score. [2, -5, -2] gives 20, because the second negative card turned -10 upside down. [-2, -4] gives 8. [-2, -4, 3] gives 24. The whole row gives 2 x -5 x -2 x -4 x 3 = -240, because it holds three negative cards. Trying the rest confirms that 24, from a[2..4], is the best.
Notice what happened with [2, -5]. Its score, -10, looked like the worst so far, yet one more card made it 20. That single observation is the whole difficulty of this problem, and once we have seen it clearly, the solution is a short loop. The problem is smaller than it looks.
Each cell is one card. The highlighted run of neighbouring cards has the largest product.
- best product
- 24
- whole array
- -240
- a[0..2]
- 20
1The best run is a[2..4]: (-2) x (-4) x 3 = 24. Two negative cards cancel each other out, and the 3 makes the result larger still.
What to assume
- Can there be negative numbers and zeros?
- Yes, and they are what make the problem interesting.
- Must the run be non-empty?
- Yes, so for [-3] the answer is -3, not 1.
- Can the array itself be empty?
- We assume it has at least one element.
- Does the product fit in an int?
- We assume so, as the usual statement promises.
A careful candidate asks a few questions first. Can there be negative numbers and zeros? Yes, and they are what make the problem interesting. Must the run be non-empty? Yes, so for [-3] the answer is -3, not 1. Can the array itself be empty? We assume it has at least one element. Does the product fit in an int? We assume so, as the usual statement promises, and return to overflow at the end.
Your turn
Solve it before you read on. Above is one example with the result expected for it. Under What to assume are the points this solution takes as given. Say your approach aloud or type it below, and write the code in your own editor. Then take one hint at a time and compare.
2How to recognise that this is dynamic programming
Many beginners who meet this question have just learned the maximum sum subarray, and their first thought is to copy that solution with a times sign in place of the plus. Others reach for a sliding window, because the question talks about a run of neighbours. Both feelings are reasonable, and it helps to see which words in the question lead where.
The first clue is the word contiguous. A contiguous run must end somewhere, so we can ask a smaller question at every index: what is the best run that ends exactly here? Any run ending at index i is either a[i] alone, or a[i] joined to a run that ended at index i - 1. So the answer at i can be built from the answer at i - 1.
The second clue is the word largest. We are optimising, picking the best among many choices, and we would like to throw away all the choices that cannot win. This is where the third clue, the word product, becomes a warning. With sums, a small total is never useful later. With products, a negative card can turn the smallest total into the largest, so we must be careful about what we throw away.
These clues point to dynamic programming. The name sounds grand, but it only means solving a problem from the answers to slightly smaller versions of it, and remembering those answers instead of recomputing them. Here the smaller versions are the best runs ending at each earlier index. The rule to carry to new problems is this. For the best contiguous run of anything, describe the best run ending at index i, then ask what you must remember about index i - 1 to build it. For sums one number is enough. For products, as we will see, we need two.
Two other patterns look close but do not fit. A sliding window needs a rule for when to shrink the window, and products give none, because one more card can make the score much bigger or much smaller depending on its sign. Prefix products with division, dividing a running product by an earlier one, fail at the first zero, because we cannot divide by zero.
3The brute force, trying every run
The honest first attempt is to try every run. We pick a start index i, then walk forward with an end index j, multiplying in one more card each step, and keep the largest product seen. Multiplying forward is already a little clever, because the product of a[i..j] is the product of a[i..j - 1] times a[j], so each run costs one multiplication rather than a fresh loop. This brute force is correct and easy to trust, which makes it a good start.
Let us count on the example. Start 0 has five runs, start 1 has four, then three, two and one, so there are 5 + 4 + 3 + 2 + 1 = 15 runs and 15 multiplications, and the largest product found is 24. For n cards that is n(n + 1) / 2 multiplications, which grows like n squared, written O(n squared). The extra memory is two variables, so the space is O(1).
Where is the waste? Look at the runs that end at index 4: a[0..4], a[1..4], a[2..4], a[3..4] and a[4..4]. The brute force builds each from a different start, in a different pass of the outer loop, and never connects them. Yet they are all one card longer than the runs that ended at index 3. If we already knew the useful facts about runs ending at index 3, we could get the best run ending at index 4 with one or two multiplications, and walk the array once.
4From the waste to the max and min idea, one step at a time
Let us try the most natural improvement first, exactly the one that works for sums. We keep one number, the best product of a run ending at the current index, call it run. At each new card we either extend the old run or start fresh with the card alone, and we take the bigger of the two. The picture runs this on a short row, [-2, 3, -4], whose true answer is 24, the whole row.
run is the best product of a run ending at the current card, as the copied idea defines it. The true answer for [-2, 3, -4] is 24.
- run
- -2
- best
- -2
1At index 0 the only run is [-2], so run = -2 and best = -2.
- run
- 3
- forgotten
- -6 from a[0..1]
- best
- 3
2At index 1 we choose between 3 alone and -2 x 3 = -6. 3 is bigger, so run = 3, and the -6 is thrown away as a bad result.
- run
- -4
- best
- 3, wrong
- missed
- -6 x -4 = 24
3At index 2 we choose between -4 alone and 3 x -4 = -12, so run = -4 and best stays 3. But -6 x -4 = 24 was the real answer.
It answers 3, not 24. Why did it fail? A beginner might suspect a bug in the arithmetic, but every step did exactly what we told it. The mistake is in what we decided to forget. At index 1 we compared 3 with -6 and kept 3, throwing -6 away as a poor result. But -6 was precisely the run that the next card, -4, turns into 24. With sums a small total is never useful, because adding a number to something small always gives less than adding it to something big. With products, multiplying by a negative number reverses the order, so the smallest product becomes the largest.
So what must we remember at each index? Two numbers. maxHere is the largest product of a run ending exactly at index i, and minHere is the smallest. When the next card x is positive, the largest new product comes from extending maxHere, and the smallest from extending minHere, so nothing surprising happens. When x is negative, the roles flip. The largest new product comes from extending minHere, the most negative score, and the smallest from extending maxHere.
The code expresses that flip neatly. If x is negative, we first swap maxHere and minHere. After the swap, the same two lines work for every card: maxHere = max(x, maxHere * x) and minHere = min(x, minHere * x). The x on its own in each line is the choice to start fresh at this card.
Here is a question a beginner often asks. Why do we need to start fresh at all, if we already extend both the largest and the smallest? Because of zeros. After a 0, both maxHere and minHere become 0, and every longer run through that 0 is stuck at 0. Starting fresh lets the run begin again at the next card. The answer is the largest maxHere seen at any index, because the best run has to end somewhere, and we keep it in a third variable, best.
Why is this correct? At every index, maxHere and minHere really are the largest and smallest products of runs ending there, because any run ending at i is a[i] alone or a run ending at i - 1 times a[i], and multiplying by a fixed number sends the largest and smallest old products to the extremes of the new ones. Since we look at every index, the best run is found at its last card.
5Watching both running products on 2, -5, -2, -4, 3
The picture runs the real loop on our example. For each negative card there are two frames, one for the swap and one for the update, so you can see the flip happen. The marked cells are the run behind maxHere, and the panel shows maxHere, minHere and best, each with the run it comes from.
Keep your eye on the negative numbers in the panel. A large negative minHere is not a failure; it is a score waiting for the next negative card.
i is the card we are on. The marked cells are the run behind maxHere. The panel shows both running products and the best so far.
- a[i]
- 2
- step
- first card
- maxHere
- 2 = a[0..0]
- minHere
- 2 = a[0..0]
- best
- 2 = a[0..0]
1We start on the first card. The only run ending at index 0 is [2], so
maxHere,minHereand best are all 2.- a[i]
- -5
- step
- negative: swap
- maxHere
- 2 = a[0..0]
- minHere
- 2 = a[0..0]
- best
- 2 = a[0..0]
2a[1] = -5 is negative, so we swap
maxHereandminHere. Both are 2, so nothing visible changes this time.- a[i]
- -5
- step
- extend or restart
- maxHere
- -5 = a[1..1]
- minHere
- -10 = a[0..1]
- best
- 2 = a[0..0]
3Now
maxHere=max(-5, 2 x -5)= -5, starting fresh, andminHere=min(-5, 2 x -5)= -10, from a[0..1]. best stays 2.- a[i]
- -2
- step
- negative: swap
- maxHere
- -10 = a[0..1]
- minHere
- -5 = a[1..1]
- best
- 2 = a[0..0]
4a[2] = -2 is negative, so we swap.
maxHerenow holds -10 andminHereholds -5, ready to be flipped by the minus sign.- a[i]
- -2
- step
- extend or restart
- maxHere
- 20 = a[0..2]
- minHere
- -2 = a[2..2]
- best
- 20 = a[0..2]
5
maxHere=max(-2, -10 x -2)= 20, the old minimum turned into a maximum.minHere=min(-2, -5 x -2)= -2. best becomes 20.- a[i]
- -4
- step
- negative: swap
- maxHere
- -2 = a[2..2]
- minHere
- 20 = a[0..2]
- best
- 20 = a[0..2]
6a[3] = -4 is negative, so we swap again.
maxHereis -2 andminHereis 20, the large value now waiting on the minimum side.- a[i]
- -4
- step
- extend or restart
- maxHere
- 8 = a[2..3]
- minHere
- -80 = a[0..3]
- best
- 20 = a[0..2]
7
maxHere=max(-4, -2 x -4)= 8, from a[2..3].minHere=min(-4, 20 x -4)= -80. best stays 20, since 8 is smaller.- a[i]
- 3
- step
- extend or restart
- maxHere
- 24 = a[2..4]
- minHere
- -240 = a[0..4]
- best
- 24 = a[2..4]
8a[4] = 3 is positive, so no swap.
maxHere=max(3, 8 x 3)= 24 andminHere=min(3, -80 x 3)= -240. best becomes 24.- answer
- 24
- best run
- a[2..4]
9The loop has finished. The largest product we recorded is 24, from a[2..4], the run -2, -4, 3, and that is the answer.
Let us read the important frames back. At index 1, minHere becomes -10, from [2, -5], the very kind of run the copied idea would have forgotten. At index 2 the swap moves -10 into maxHere, and multiplying by -2 turns it into 20. That is the moment the minimum becomes the maximum, and best jumps to 20.
At index 3 the same thing happens the other way. 20 moves to the minimum side and becomes -80, while the -2 that started fresh at index 2 is multiplied by -4 to give 8, from a[2..3]. best stays 20 for now.
At index 4 the card is positive, so there is no swap, and 8 x 3 gives 24, from a[2..4]. best becomes 24. Notice that minHere ended at -240, the product of the whole row. We kept it because a later negative card could have turned it into a winner. Here the row simply ended first.
6The complete Java program
Here is the full program. main runs the classic example [2, 3, -2, 4], a row where two negatives cancel, a row with a zero, a single negative card, and our traced example, and each comment shows what that line prints.
Let us read maxProduct in the order it runs. The first line sets maxHere, minHere and best all to a[0]. Why not start them at 1, a beginner may ask? Because 1 would be the product of an empty run, which the question does not allow. For [-3], starting at 1 would answer 1, but the only run is [-3], so the answer must be -3.
The loop then visits each card from index 1. We copy the card into x. If x is negative, the three lines with tmp swap maxHere and minHere. Then maxHere becomes the larger of x alone and maxHere * x, and minHere the smaller of x alone and minHere * x. Finally best keeps the largest maxHere seen so far.
The mistake beginners most often make comes from skipping the swap. They write maxHere = max(x, maxHere * x, minHere * x) and then minHere = min(x, maxHere * x, minHere * x), but by the second line maxHere already holds its new value, so minHere is built from the wrong number. The swap version avoids that trap, because after the swap each line reads only its own old value. So main prints 6, 24, 0, -3 and 24.
7How much it costs, and the cases at the edges
Let us count on the example first. The loop visited the four cards after the first, and for each one did at most a swap, two multiplications, and three comparisons, about a dozen small operations per card. The brute force needed 15 multiplications for five cards and needs n(n + 1) / 2 for n cards. Our loop needs about 2n, so the time is O(n). We keep maxHere, minHere, best and x, four ints, whatever the length, so the space is O(1).
| Approach | Time | Space | Correct? |
|---|---|---|---|
| Brute force over every run | O(n^2) | O(1) | yes |
| Copy of the sum idea, best product only | O(n) | O(1) | no, misses sign flips |
| Largest and smallest product ending here | O(n) | O(1) | yes |
The edge cases are handled by the same lines. A single card is returned as it is, even when negative, because everything starts at a[0]. A zero resets both running products to 0, and since x on its own is always a candidate, the run restarts on the next card; for [-2, 0, -1] the answer is 0, from the zero itself. All negative cards are fine too: for [-2, -3] the answer is 6.
The real danger is overflow. Products grow very fast, and ten cards of value 10 already exceed the largest int. Java does not warn us; the value silently wraps around to a wrong number. If the inputs may be large, we make the variables long. Remember that minHere can overflow even when the final answer fits, because it holds the most extreme negative product.
8Follow-up questions
Is there another way to see this problem?
Yes. Between zeros, a run with an even number of negative cards has a positive product, and a longer such run is never worse. So inside a stretch without zeros, the best run either uses the whole stretch, or drops everything up to and including the first negative card, or drops everything from the last negative card on. We can catch all of these by multiplying from the left and, separately, from the right, restarting at each zero, and taking the largest product seen in either pass. That is also O(n) time and O(1) space.
What if we also need the run itself, not only the product?
We keep a start index beside maxHere and another beside minHere. When a value starts fresh at card i, its start becomes i, and when we swap the two values we swap their starts too. Whenever best improves, we record the start of maxHere and the current index i. On our example that gives a[2..4]. The panel in the walk-through picture shows exactly these starts.
Why do we not need the minimum in the maximum sum problem?
Because adding a number keeps the order of totals. If one total is smaller than another, adding the same x to both leaves it smaller, so the smallest total can never overtake the largest. Multiplying by a negative x reverses the order, and multiplying by zero erases it. That one difference in arithmetic is why the product version must carry the minimum along.
9Conclusion
We found the largest product of a contiguous run by keeping, for each index, both the largest and the smallest product of a run ending there, because a negative card turns the smallest into the largest. Swapping the two on a negative card, and letting each restart at the card alone, handles sign flips and zeros in one pass, with O(n) time and O(1) space. We start from a[0] so a single negative card is right, and we switch to long when products may grow large. The clue to remember is a best contiguous run built by extend or restart at each index: that is dynamic programming, and a sign flip means we must carry the minimum too.
Open with
Let me confirm: the run must be non-empty and contiguous, and the array may hold negatives and zeros. The brute force multiplies forward from every start, which is O(n squared).
Then, if they want more
Since this is the best contiguous run, I think in terms of the best run ending at each index, which is dynamic programming. Copying the sum version and keeping only the best product fails, because a negative number flips the order: in minus two, three, minus four, the run minus six looks bad, but times minus four it becomes twenty-four.
So I keep two values for runs ending at the current index, maxHere and minHere. For each new element x, if x is negative I swap them, because multiplying by a negative turns the smallest into the largest.
Then maxHere is the larger of x alone and maxHere times x, and minHere is the smaller of x alone and minHere times x. Taking x alone handles zeros, since the run can restart. I track best as the largest maxHere seen. I start all three at the first element, so a single negative number returns itself.
It is one pass, O(n) time and O(1) space. Products overflow quickly, so if values are not bounded I would use long.
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 29 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 contiguous subarray whose product is largest.": https://scrivio-interview-library.netlify.app/data-structures/solutions/find-the-contiguous-subarray-whose-product-is-largest-89f941/