https://dartpad.dev/?id=fbe51edb1837fb8190b5b79ac11949f7
Created with <3 with dartpad.dev.
https://dartpad.dev/?id=fbe51edb1837fb8190b5b79ac11949f7
Created with <3 with dartpad.dev.
// Don't you ever write code like this. | |
// -- Ntrf | |
import 'dart:math'; | |
int waterTrapped(List<int> heights) { | |
int maxFwd = 0; | |
int maxRev = 0; | |
int res = heights.fold(0, (a, x) => a + (maxFwd = max(maxFwd, x))); | |
res += heights.reversed.fold(0, (a, x) => a + (maxRev = max(maxRev, x))); | |
return heights.fold(res, (a, x) => (a - x - maxFwd)); | |
} | |
void run(List<int> list, int exp) => | |
print("$list => ${waterTrapped(list)} ($exp expected)"); | |
void main() { | |
run([0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1], 6); | |
run([4, 2, 0, 3, 2, 5], 9); | |
run([],0); | |
run([0,0,0,0,0],0); | |
run([0,0,1,0,0],0); | |
run([1,0,0,0,1],3); | |
} |