Find the best contiguous sum in one pass, even with negative values.
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.
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;
}def 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;
}def 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);
}This version starts best_here and best_so_far at 0, which quietly allows an empty run.
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.
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.
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.
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.
systemdesignmastery.dev/dsa/cheatsheets/kadane