Find the best contiguous sum in one pass, even with negative values.
Use it when the task asks for the best total of a block of neighbouring values, and the values can be negative. Signal words: best consecutive stretch, contiguous run, largest sum of neighbouring values, one pass.
Start best_here and best_so_far both equal the first value.
Step for each later value, set best_here to the larger of the value alone and best_here plus the value. Then keep the larger of best_so_far and best_here.
Stop after the last value. Return best_so_far.
It does not answer a question about an exact total or a fixed length. Those need a prefix-sum map or a sliding window.
Cost: O(n) time and O(1) extra space.
In this lesson you find the best block of neighbouring values in one pass, even when some values are negative. Two numbers are enough: the best block that ends here, and the best block so far.
You work on the sales dashboard of an online store. For each day it shows the net revenue change in units: sales add to it, and refunds take from it. Some days are negative.
Your team lead says: Marketing wants the best stretch of consecutive days. Find the run with the largest total, and tell me that total.
Here is a short test: the changes for 8 days are 4, -6, 3, 5, -2, 6, -8 and 1. The best run is days 3 to 6, which are 3, 5, -2 and 6, and they add up to 12.
The real dashboard holds 100,000 days, and the values reach 10^6 in either direction. A total can then pass 2 × 10^9, so the code needs 64-bit integers.
You walk along a row of market stalls with a bag. At each stall a seller adds coins to your bag or takes coins from it, and the amounts can be negative.
At every stall you ask one question: is the bag I carry worth keeping? If it holds less than nothing, you drop it and start a new bag at this stall. The best bag you ever held, at any stall, is the answer.
Like a walk past market stalls with a bag: keep it while it is worth keeping, drop it below zero, and note the best bag held.
Before you write code, find the best run in the eight days by hand. Watch what you carry from one day to the next.
Solve it by hand: Eight days: the best run, one value at a time. The hand-solve sheet loads in your browser.
At each day you hold one number: the total of the best run that ends on that day. A new day can add its value to that run, or leave the run behind and start again.
The values are 4, -6, 3, 5, -2, 6, -8 and 1. The first day starts the first run, so both numbers start at 4.
| Place | Value | Extend | Start again | best_here | best_so_far |
|---|---|---|---|---|---|
| 0 | 4 | 4 | 4 | ||
| 1 | -6 | 4 + (-6) = -2 | -6 | -2 | 4 |
| 2 | 3 | -2 + 3 = 1 | 3 | 3 | 4 |
| 3 | 5 | 3 + 5 = 8 | 5 | 8 | 8 |
| 4 | -2 | 8 + (-2) = 6 | -2 | 6 | 8 |
| 5 | 6 | 6 + 6 = 12 | 6 | 12 | 12 |
| 6 | -8 | 12 + (-8) = 4 | -8 | 4 | 12 |
| 7 | 1 | 4 + 1 = 5 | 1 | 5 | 12 |
The answer is 12, the largest value of best_here. It is not the last value, 5. At place 2 the old run was worth -2, so starting again at 3 was better.
Start with a correct version. It adds up every run from every start day to every end day, and keeps the largest total.
def best_run_sum_first(values):
best = values[0]
for start in range(len(values)):
total = 0
for end in range(start, len(values)): # the run from start to end
total += values[end]
best = max(best, total)
return bestThis is correct. On the test list it looks at 36 runs, which is instant.
Now check the real size.
The dashboard holds 100,000 days. An addition takes about 1 nanosecond.
Here is the count from running the code:
So the dashboard is about five times too slow for a one-second refresh.
Predict the cost
Q The first attempt adds up the runs from every start to every end. How does the number of runs grow when the list has twice as many days?
Answer: B
There are n(n + 1) / 2 runs, so doubling n multiplies the count by about 4. Ten times more days means about a hundred times more runs.
The first attempt is correct, but it adds the same days again and again. Now look at what two neighbouring runs share.
Look at the hand trace again. At each day you did not need every run. You needed one number: the best run that ends on that day.
That number has a simple rule. A run that ends today is either today's value alone, or a run that ended yesterday with today's value added. The best such run extends yesterday's best run, or starts again.
So best_here = max(value, best_here + value). It starts again exactly when yesterday's best run is negative, because a negative run only lowers any total it joins.
The best run overall ends on some day. So keep a second number, best_so_far, which is the largest best_here seen on any day. The answer is best_so_far.
Here is the same list, counted both ways:
| Method | Runs examined or values visited |
|---|---|
| Every start and every end | 5,000,050,000 runs |
| One pass with two numbers | 100,000 values |
The pass is about 50,000 times shorter. At 1 nanosecond a step it takes about 0.1 milliseconds.
Race: Finding the best run: every start and end against one pass. The operation counter loads in your browser.
At 1,000 days the first attempt looks at 500,500 runs and the pass visits 1,000 values. At 10,000 days the counts are 50,005,000 against 10,000.
At each value, the best run that ends here extends the run before it, or starts again at this value: whichever total is larger.
The values are [5, -9, 4, 6, -3, 7, -20, 8, 2]. The player stops at five steps and asks you to predict a number.
Dry run: Predict each step: nine days. The step-by-step player loads in your browser.
Reading without the player? Cover the last two columns and predict them row by row.
| Place | Value | best_here | best_so_far |
|---|---|---|---|
| 0 | 5 | 5 | 5 |
| 1 | -9 | -4 | 5 |
| 2 | 4 | 4 | 5 |
| 3 | 6 | 10 | 10 |
| 4 | -3 | 7 | 10 |
| 5 | 7 | 14 | 14 |
| 6 | -20 | -6 | 14 |
| 7 | 8 | 8 | 14 |
| 8 | 2 | 10 | 14 |
The answer is 14, the run 4, 6, -3 and 7. At the end best_here is 10, and it is not the answer, because the best run ended at place 5.
Exercise · Predict the output: The two numbers at the end. The loop carries best_here and best_so_far along the days. What does this print?
values = [3, -4, 2, -1, -3, 5, -2]
best_here = best_so_far = values[0]
for i in range(1, len(values)):
best_here = max(values[i], best_here + values[i])
best_so_far = max(best_so_far, best_here)
print(best_here, best_so_far)Here is the rule that keeps the algorithm correct. Every line of the templates exists to protect it.
After each place, best_here is the largest sum of a run that ends at that place, and best_so_far is the largest best_here seen up to it.
Before the first value there are no runs. After the first value, the only run is that value, so both numbers equal it. Each new value either extends the best run that ended before it or starts a new one, and both choices are covered by the max.
When the pass ends, every run has ended at some place. So the largest best_here is the largest run sum.
Use it when the task asks for the best total of a block of neighbouring values, and the values can be negative. Signal words: best consecutive stretch, contiguous run, largest sum of neighbouring values, one pass.
Start: best_here and best_so_far both equal the first value.
Step: for each later value, set best_here to the larger of the value alone and best_here plus the value. Then keep the larger of best_so_far and best_here.
Stop: after the last value. Return best_so_far.
It does not answer a question about an exact total or a fixed length. Those need a prefix-sum map or a sliding window.
Cost: O(n) time and O(1) extra space.
def best_run_sum(values):
# [1] The first value starts the first run; with all-negative data the best run is one value, so never start at 0.
best_here = values[0]
best_so_far = values[0]
# [2] Visit every later value once.
for i in range(1, len(values)):
# [3] Extend the best run that ends one place earlier, or start a new run here: whichever is larger.
best_here = max(values[i], best_here + values[i])
# [4] Keep the largest best here seen at any place.
best_so_far = max(best_so_far, best_here)
# [5] Return the best sum of any run.
return best_so_farpublic long bestRunSum(int[] values) {
// [1] The first value starts the first run; with all-negative data the best run is one value, so never start at 0.
long bestHere = values[0];
long bestSoFar = values[0];
// [2] Visit every later value once.
for (int i = 1; i < values.length; i++) {
// [3] Extend the best run that ends one place earlier, or start a new run here: whichever is larger.
bestHere = Math.max(values[i], bestHere + values[i]);
// [4] Keep the largest best here seen at any place.
bestSoFar = Math.max(bestSoFar, bestHere);
}
// [5] Return the best sum of any run.
return bestSoFar;
}long long bestRunSum(vector<int>& values) {
// [1] The first value starts the first run; with all-negative data the best run is one value, so never start at 0.
long long bestHere = values[0];
long long bestSoFar = values[0];
// [2] Visit every later value once.
for (int i = 1; i < (int)values.size(); i++) {
// [3] Extend the best run that ends one place earlier, or start a new run here: whichever is larger.
bestHere = max((long long)values[i], bestHere + values[i]);
// [4] Keep the largest best here seen at any place.
bestSoFar = max(bestSoFar, bestHere);
}
// [5] Return the best sum of any run.
return bestSoFar;
}function bestRunSum(values) {
// [1] The first value starts the first run; with all-negative data the best run is one value, so never start at 0.
let bestHere = values[0];
let bestSoFar = values[0];
// [2] Visit every later value once.
for (let i = 1; i < values.length; i++) {
// [3] Extend the best run that ends one place earlier, or start a new run here: whichever is larger.
bestHere = Math.max(values[i], bestHere + values[i]);
// [4] Keep the largest best here seen at any place.
bestSoFar = Math.max(bestSoFar, bestHere);
}
// [5] Return the best sum of any run.
return bestSoFar;
}Rebuild the template: put its lines back in order. Loads in your browser.
Exercise · Put it in order: The best stretch of days. Arrange the lines into a function that returns the largest total of any run of neighbouring days.
def best_run_sum(values):
best_here = values[0]
best_so_far = values[0]
for i in range(1, len(values)):
best_here = max(values[i], best_here + values[i])
best_so_far = max(best_so_far, best_here)
return best_so_far
best_here = 0
return best_heredef best_product_run(values):
# [1] The first value starts the first run, as both the biggest and the smallest product that ends there.
biggest_here = values[0]
smallest_here = values[0]
best_so_far = values[0]
# [2] Visit every later value once.
for i in range(1, len(values)):
value = values[i]
# [3] A negative value swaps the roles, so try the value alone and both old products times it.
times_biggest = biggest_here * value
times_smallest = smallest_here * value
biggest_here = max(value, times_biggest, times_smallest)
smallest_here = min(value, times_biggest, times_smallest)
# [4] Keep the largest biggest here seen at any place.
best_so_far = max(best_so_far, biggest_here)
# [5] Return the best product of any run.
return best_so_farpublic long bestProductRun(int[] values) {
// [1] The first value starts the first run, as both the biggest and the smallest product that ends there.
long biggestHere = values[0];
long smallestHere = values[0];
long bestSoFar = values[0];
// [2] Visit every later value once.
for (int i = 1; i < values.length; i++) {
long value = values[i];
// [3] A negative value swaps the roles, so try the value alone and both old products times it.
long timesBiggest = biggestHere * value;
long timesSmallest = smallestHere * value;
biggestHere = Math.max(value, Math.max(timesBiggest, timesSmallest));
smallestHere = Math.min(value, Math.min(timesBiggest, timesSmallest));
// [4] Keep the largest biggest here seen at any place.
bestSoFar = Math.max(bestSoFar, biggestHere);
}
// [5] Return the best product of any run.
return bestSoFar;
}long long bestProductRun(vector<int>& values) {
// [1] The first value starts the first run, as both the biggest and the smallest product that ends there.
long long biggestHere = values[0];
long long smallestHere = values[0];
long long bestSoFar = values[0];
// [2] Visit every later value once.
for (int i = 1; i < (int)values.size(); i++) {
long long value = values[i];
// [3] A negative value swaps the roles, so try the value alone and both old products times it.
long long timesBiggest = biggestHere * value;
long long timesSmallest = smallestHere * value;
biggestHere = max(value, max(timesBiggest, timesSmallest));
smallestHere = min(value, min(timesBiggest, timesSmallest));
// [4] Keep the largest biggest here seen at any place.
bestSoFar = max(bestSoFar, biggestHere);
}
// [5] Return the best product of any run.
return bestSoFar;
}function bestProductRun(values) {
// [1] The first value starts the first run, as both the biggest and the smallest product that ends there.
let biggestHere = values[0];
let smallestHere = values[0];
let bestSoFar = values[0];
// [2] Visit every later value once.
for (let i = 1; i < values.length; i++) {
const value = values[i];
// [3] A negative value swaps the roles, so try the value alone and both old products times it.
const timesBiggest = biggestHere * value;
const timesSmallest = smallestHere * value;
biggestHere = Math.max(value, timesBiggest, timesSmallest);
smallestHere = Math.min(value, timesBiggest, timesSmallest);
// [4] Keep the largest biggest here seen at any place.
bestSoFar = Math.max(bestSoFar, biggestHere);
}
// [5] Return the best product of any run.
return bestSoFar;
}A zero and two sign flips, traced on values = [2, -3, 0, -2, -4, 3]:
| Place | Value | biggest_here | smallest_here | best_so_far |
|---|---|---|---|---|
| 0 | 2 | 2 | 2 | 2 |
| 1 | -3 | -3 | -6 | 2 |
| 2 | 0 | 0 | 0 | 2 |
| 3 | -2 | 0 | -2 | 2 |
| 4 | -4 | 8 | -4 | 8 |
| 5 | 3 | 24 | -12 | 24 |
The zero resets both numbers, because every run through it multiplies to 0. At place 4 the smallest product, -2, times -4 becomes the biggest, 8. The answer is 24, from -2, -4 and 3.
Exercise · Break it: The product that never restarts. This best-product code keeps the biggest and smallest product, but it forgets that a run can start again at the current value. Find a list where it gives the wrong answer.
def best_product_run(values):
biggest_here = values[0]
smallest_here = values[0]
best_so_far = values[0]
for i in range(1, len(values)):
value = values[i]
times_biggest = biggest_here * value
times_smallest = smallest_here * value
biggest_here = max(times_biggest, times_smallest)
smallest_here = min(times_biggest, times_smallest)
best_so_far = max(best_so_far, biggest_here)
return best_so_fardef best_circular_run(values):
# [1] Start the best run, the worst run and the total from the first value.
best_here = values[0]
best_so_far = values[0]
worst_here = values[0]
worst_so_far = values[0]
total = values[0]
# [2] Visit every later value once.
for i in range(1, len(values)):
# [3] Update the best and the worst run that end here in the same way, and add to the total.
best_here = max(values[i], best_here + values[i])
best_so_far = max(best_so_far, best_here)
worst_here = min(values[i], worst_here + values[i])
worst_so_far = min(worst_so_far, worst_here)
total += values[i]
# [4] When every value is negative, a wrapping run would be empty, so the best single run stands.
if best_so_far < 0:
return best_so_far
# [5] Otherwise the answer stays inside the row, or wraps: the total minus the worst run.
return max(best_so_far, total - worst_so_far)public long bestCircularRun(int[] values) {
// [1] Start the best run, the worst run and the total from the first value.
long bestHere = values[0];
long bestSoFar = values[0];
long worstHere = values[0];
long worstSoFar = values[0];
long total = values[0];
// [2] Visit every later value once.
for (int i = 1; i < values.length; i++) {
// [3] Update the best and the worst run that end here in the same way, and add to the total.
bestHere = Math.max(values[i], bestHere + values[i]);
bestSoFar = Math.max(bestSoFar, bestHere);
worstHere = Math.min(values[i], worstHere + values[i]);
worstSoFar = Math.min(worstSoFar, worstHere);
total += values[i];
}
// [4] When every value is negative, a wrapping run would be empty, so the best single run stands.
if (bestSoFar < 0) {
return bestSoFar;
}
// [5] Otherwise the answer stays inside the row, or wraps: the total minus the worst run.
return Math.max(bestSoFar, total - worstSoFar);
}long long bestCircularRun(vector<int>& values) {
// [1] Start the best run, the worst run and the total from the first value.
long long bestHere = values[0];
long long bestSoFar = values[0];
long long worstHere = values[0];
long long worstSoFar = values[0];
long long total = values[0];
// [2] Visit every later value once.
for (int i = 1; i < (int)values.size(); i++) {
// [3] Update the best and the worst run that end here in the same way, and add to the total.
bestHere = max((long long)values[i], bestHere + values[i]);
bestSoFar = max(bestSoFar, bestHere);
worstHere = min((long long)values[i], worstHere + values[i]);
worstSoFar = min(worstSoFar, worstHere);
total += values[i];
}
// [4] When every value is negative, a wrapping run would be empty, so the best single run stands.
if (bestSoFar < 0) {
return bestSoFar;
}
// [5] Otherwise the answer stays inside the row, or wraps: the total minus the worst run.
return max(bestSoFar, total - worstSoFar);
}function bestCircularRun(values) {
// [1] Start the best run, the worst run and the total from the first value.
let bestHere = values[0];
let bestSoFar = values[0];
let worstHere = values[0];
let worstSoFar = values[0];
let total = values[0];
// [2] Visit every later value once.
for (let i = 1; i < values.length; i++) {
// [3] Update the best and the worst run that end here in the same way, and add to the total.
bestHere = Math.max(values[i], bestHere + values[i]);
bestSoFar = Math.max(bestSoFar, bestHere);
worstHere = Math.min(values[i], worstHere + values[i]);
worstSoFar = Math.min(worstSoFar, worstHere);
total += values[i];
}
// [4] When every value is negative, a wrapping run would be empty, so the best single run stands.
if (bestSoFar < 0) {
return bestSoFar;
}
// [5] Otherwise the answer stays inside the row, or wraps: the total minus the worst run.
return Math.max(bestSoFar, total - worstSoFar);
}The wrap traced on values = [6, -2, -7, 3, 5]:
| Place | Value | best_here | best_so_far | worst_here | worst_so_far | total |
|---|---|---|---|---|---|---|
| 0 | 6 | 6 | 6 | 6 | 6 | 6 |
| 1 | -2 | 4 | 6 | -2 | -2 | 4 |
| 2 | -7 | -3 | 6 | -9 | -9 | -3 |
| 3 | 3 | 3 | 6 | -6 | -9 | 0 |
| 4 | 5 | 8 | 8 | -1 | -9 | 5 |
The best run inside the row is 8, from 3 and 5. The worst run is -2 and -7, so the wrapping run is 5 - (-9) = 14: the values 3, 5 and 6. The answer is 14.
For a product, keep the biggest and the smallest product that end here, because a negative value turns the smallest into the largest.
Exercise · Find the bug: The wrap that loses the worst run. This circular best-run code gives too small an answer on some rows where the best run wraps round the end. Which line is wrong?
def best_circular_run(values):
best_here = values[0]
best_so_far = values[0]
worst_here = values[0]
worst_so_far = values[0]
total = values[0]
for i in range(1, len(values)):
best_here = max(values[i], best_here + values[i])
best_so_far = max(best_so_far, best_here)
worst_here = min(values[i], worst_here + values[i])
worst_so_far = min(worst_so_far, worst_here)
total += values[i]
if best_so_far < 0:
return best_so_far
return max(best_so_far, total - worst_here)The three templates answer three kinds of question. You can pick before you write any code.
Then check the ends: what do the templates do when every value is negative, when a value is 0, and when there is one value?
| Situation | Method | Why |
|---|---|---|
| Best sum of a block | Extend or start again | One number carries the best run forward |
| Best product of a block | Biggest and smallest | A negative value swaps them |
| Best block on a circle | Best inside, or total minus worst | A wrapping block is the rest of the circle |
| Best buy then sell | Kadane on the differences | A profit is the sum of the daily changes between the two days |
A savings app shows the unit price of a fund for 6 days: 9, 4, 7, 3, 8 and 6. You buy on one day and sell on a later day. What is the best profit?
The day-to-day changes are -5, 3, -4, 5 and -2. A profit is the sum of the changes between the buy day and the sell day, which is a run.
| Place | Change | best_here | best_so_far |
|---|---|---|---|
| 0 | -5 | -5 | -5 |
| 1 | 3 | 3 | 3 |
| 2 | -4 | -1 | 3 |
| 3 | 5 | 5 | 5 |
| 4 | -2 | 3 | 5 |
The best run is the single change of 5, from the fourth day to the fifth: buy at 3 and sell at 8, a profit of 5.
Real data brings edge cases.
For values = [-5, -2, -9], every run lowers the total, so the best run is the single largest value. Both numbers start at -5, then best_so_far becomes -2. The answer is -2.
For values = [7], the loop does not run. Both numbers equal 7, and the answer is 7. For [-4] the answer is -4.
For values = [0, 0, 0], extending and starting again give the same total, 0. The answer is 0, and the choice does not matter.
For values = [2000000000, -1, 2000000000], the whole list adds up to 3,999,999,999. That is more than a 32-bit integer holds, so the totals must be 64-bit.
This version starts best_here and best_so_far at 0, which quietly allows an empty run.
Counterexample: values = [-5, -2, -9]. The version returns 0. The best non-empty run is the single value -2.
Start both numbers from the first value, so every run has at least one value.
This version returns best_here after the last place. That is the best run that ends on the last day, and the best run overall can end earlier.
Counterexample: values = [5, -1, -10]. At the end best_here is -6, but the best run is the single value 5.
Return best_so_far, the largest best_here seen at any place.
Starting both numbers at 0 allows an empty run, so a list of only negative values returns 0 instead of its largest single value.
This version keeps only the biggest product that ends here, with max(value, biggest_here * value). A negative value can turn a very small product into a very large one, and the version has thrown the small product away.
Counterexample: values = [-2, 3, -4]. The version returns 3. The whole list multiplies to 24.
Keep the smallest product that ends here as well.
This version always returns the larger of the best run and the total minus the worst run. When every value is negative, the worst run is the whole row, so the total minus the worst run is 0, an empty run.
Counterexample: values = [-3, -1, -2]. The version returns 0. The best non-empty run is -1.
When best_so_far is negative, return it, as template 3 does.
Finance asks for the runs of days that add up to exactly 100 units. Kadane keeps only the best total, so it cannot test for equality.
For this question, keep a running prefix total and a map of the totals seen so far. That is the prefix-sum map pattern of the hashing module.
Your team lead brings four product changes.
Marketing wants the first and last day of the best run, not only the total. Remember the start of the current run: it moves to the current place when you start again. When best_so_far improves, save that start and the current place.
A savings app wants the best profit from one buy and a later sell, or 0 when prices only fall. Take the daily changes and run template 1, but start again at 0 and allow an empty run. This is LeetCode 121: Best Time to Buy and Sell Stock.
A monitoring chain multiplies a gain at each stage, and a stage can be negative. Use template 2, with the biggest and the smallest product. This is LeetCode 152: Maximum Product Subarray.
A loop route repeats, so a shift can start near the end and wrap to the start. Use template 3. For [5, -3, 4] the best run inside the row is 6, and the wrapping run 4, 5 is 9, which is the total 6 minus the worst run -3. This is LeetCode 918: Maximum Sum Circular Subarray.
Explain it back: write the idea in your own words and get feedback.
In two or three sentences, explain to a teammate how you find the best run of consecutive values in one pass. Then say why the algorithm starts from the first value, and what it costs. The AI tutor checks your answer against the invariant and the key points of this lesson.
Here is how you could explain it in an interview, now that you have counted it.
I walk the array once and keep two numbers. Best here is the largest sum of a run that ends at this place. It is the larger of the value alone and best here plus the value.
Best so far is the largest best here seen at any place, and it is the answer. Both start from the first value, so an array with only negative values returns its largest single value.
The pass costs O of n time and O of 1 space. Checking every start and end would cost n times n over two.
For the best run of neighbouring values, I keep two numbers while I walk the array once. Best here is the largest sum of a run that ends at this place. Best so far is the largest best here that I have seen.
At each value, best here becomes the larger of the value alone and best here plus the value. It starts a new run exactly when the old run is negative. Then I update best so far. I start both from the first value, so an array of negative values returns its largest single value, not zero.
That costs O of n time and O of 1 space. Trying every start and end costs about n squared over two, which is five billion steps for a hundred thousand days.
For a product, I also keep the smallest product, because a negative value flips it. On a circle I take the larger of the best run and the total minus the worst run.
Checkpoint · Best here
Q1/10 In Kadane's algorithm, what does best_here mean at a place?
Answer: B
best_here is about runs that end at this place. The largest run anywhere is best_so_far, the largest best_here seen.
Q2/10 The values are 4, -6 and 3. When does the best run ending at the third place start again at 3?
Answer: C
best_here = max(value, best_here + value). The run before is -2 here, which only lowers the total, so starting again at 3 is larger.
Q3/10 Why do both numbers start from the first value and not from 0?
Answer: C
For [-5, -2, -9] a start at 0 returns 0, but the best non-empty run is -2.
Q4/10 For the values 5, -1 and -10, which number does the function return?
Answer: B
The best run ends at the first place. best_here falls to -6 at the end, but best_so_far keeps the 5.
Q5/10 A list has 1,000 values. How many runs does the first attempt add up, from every start to every end?
Answer: C
n(n + 1) / 2 runs for n = 1,000 is 500,500. The one-pass method visits 1,000 values.
Q6/10 What does Kadane's pass cost in time and extra space?
Answer: C
One visit per value, with two numbers kept. It never stores a run.
Q7/10 A fund price list is 9, 4, 7, 3, 8 and 6. How do you find the best buy and later sell with Kadane?
Answer: B
A profit is the sum of the changes between the buy day and the sell day, which is a run. Here the best run is 5.
Q8/10 In the best product of a run, why do you also keep the smallest product ending here?
Answer: B
The most negative product times a negative value is a large positive number. For [-2, 3, -4] the answer 24 comes from that.
Q9/10 On a circle, a run that wraps past the end can be found as which quantity?
Answer: B
A wrapping run is what remains of the circle after a worst run is cut out. When every value is negative, return the best single value instead.
Q10/10 You need the runs of days whose total is exactly 100 units. Which method fits?
Answer: C
Kadane keeps only the best total and cannot test for equality. Prefix totals in a map find runs with an exact total.
Ten questions on this lesson. Pass with 80% or more to be sure the idea has landed before the next lesson.
| Step | Problem | Product line | Level | What it practises |
|---|---|---|---|---|
| 1 | Best consecutive revenue run | Shop | Easy | The core update: extend or start again |
| 2 | Best single trade in a price list | Bank | Easy | Kadane on the day-to-day differences |
| 3 | Largest product of a run | Observe | Medium | Tracking the biggest and the smallest product |
Two more problems, the best circular shift window and the worst drawdown, close this stretch as its checkpoint.
Review cards from this lesson.
Five cards from this lesson join your spaced-review deck. The first one comes back tomorrow.
Step through the idea on your own input, then build it in the lab. Runs in your browser. Step through it.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.