Coding problem
The best run of consecutive days
The task
A shop records its profit for each day; a loss is a negative number. The owner wants the best result that any stretch of consecutive days ever gave.
Complete MaxRunSum(int[] values). The array is not empty. Return the largest sum of any non-empty run of neighbouring elements. If every value is negative, the answer is the largest single value. Return a long: a sum can be larger than an int holds.
Signature
public static long MaxRunSum(int[] values)
Examples
[-2, 5, -1, 6, -20, 4]→10. 5 − 1 + 6 is the best run; the −20 makes it not worth going on.[-4, -1, -7]→-1. The run must not be empty, so the best is the single −1.
Limits: Up to 400,000 values.
The tests check: a single value (positive and negative), all values negative, all positive, a new start after a big drop, zeros, a run that goes on through small dips, two int.MaxValue values (a sum beyond int), and 400,000 values in time.
Hints
Your code
Already included: using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Threading; using System.Threading.Tasks;
public static class Solution
{
// values is not empty; returns the largest sum of a non-empty run of neighbouring values.
public static long MaxRunSum(int[] values)
{
throw new NotImplementedException();
}
}This problem comes with TechInterviewNotes Full Access
Unlock all paid content on TechInterviewNotes.