Problems › JavaScript › data
The highest so far
A stock chart underlays the running peak: after each point, how far has the price climbed at most.
- Each output entry is the largest value seen from the start up to that point.
- The result is the same length as the input.
runningMax(values: list<int>) → list<int>
Where you start
function runningMax(values) {
}
Worked examples
| Call | Result |
|---|---|
runningMax([3,1,2]) | [3,3,3] |
runningMax([1,2,3]) | [1,2,3] |
runningMax([5,-2,7]) | [5,5,7] |
runningMax([2,1,3,2]) | [2,2,3,3] |
Hint
Keep one running best and stamp it into the result after considering each value.
Reference solution in JavaScript
function runningMax(values) {
let best = 0, started = false;
const result = [];
for (const v of values) {
if (!started || v > best) { best = v; started = true; }
result.push(best);
}
return result;
}