나는 이렇게 학습한다/Algorithm & SQL

1206. Sum of positive

daco2020 2022. 12. 6. 22:35
반응형

ou get an array of numbers, return the sum of all of the positives ones.

Example [1,-4,7,12] => 1 + 7 + 12 = 20

Note: if there is nothing to sum, the sum is default to 0.



Solution:

int positiveSum(List<int> arr) {
  int result = 0;
  for (int a in arr) {
    if (a > 0) {
      result += a;
    }
  }
  return result;
}
int positiveSum(List<int> arr) {
  return arr.where((l) => l > 0).fold(0, (p, c) => p + c);
}
import "dart:math";

int positiveSum(List<int> xs) {
  return xs.fold(0, (a, x) => a + max(x, 0));
}


반응형

'나는 이렇게 학습한다 > Algorithm & SQL' 카테고리의 다른 글

1208. A Strange Trip to the Market  (0) 2022.12.08
1207. Vowel Count  (0) 2022.12.07
1205. Sum of Cubes  (0) 2022.12.05
1204. Odd or Even?  (0) 2022.12.04
1203. String repeat  (0) 2022.12.04