Maintain running min/max03.07
Running min/max remember the extreme seen so far. At index i they describe the slice a[0..i], not the whole array unless you are at the end.
After you see a[i]: minSoFar = min(minSoFar, a[i]), same for max. An if (a[i] < min) min = a[i] update is that move. Seed both from a[0], not from 0. If the loop starts at i=1, still record mins[0] and maxes[0] as a[0] first.
Same skill, three traces. Read all three before you try it.
01min drops, max rises - given
a = [4, 1, 9, 1]- walk
i=0: seed froma[0], somins[0]=4andmaxes[0]=4i=1:1<4so min becomes1, max stays4i=2:9>4so max becomes9, min stays1i=3:1equals min,1< max, both stay- result
- mins
[4, 1, 1, 1], maxes[4, 4, 9, 9]
02strictly decreasing - given
a = [5, 3, 0]- walk
i=0:mins[0]=5,maxes[0]=5i=1: min becomes3, max stays5i=2: min becomes0, max stays5- result
- mins
[5, 3, 0], maxes[5, 5, 5]
03single - given
a = [7]- walk
the only prefix is
a[0]mins and maxes each have length
1- result
- mins
[7], maxes[7]
runningMinMax(a).a is an array of integers. n is a.length.Return two arrays, mins and maxes, each of length
n. Seed min and max from a[0], not from 0. After index i, mins[i] is the smallest of a[0..i] and maxes[i] is the largest of a[0..i]. Include the i=0 prefix: mins[0] and maxes[0] are a[0]. Returning only the final min and max is not enough.[4, 1, 9, 1] → mins [4, 1, 1, 1], maxes [4, 4, 9, 9]. [5, 3, 0] → mins [5, 3, 0], maxes [5, 5, 5]. [7] → mins [7], maxes [7].constraintsa is non-empty.
- Best Time to Buy and Sell Stock0/3 skills ready · arrays · easyopen
- Best Time to Buy and Sell Stock0/3 skills ready · arrays · easyopen
Every Check with Awel is frozen here. Open one to read the code or load it back into the editor.