sumWithoutMaxAndMin.js (8kyu 10)

Codewars 알고리즘 풀이


Description

  • Sum all the numbers of the array except the highest and the lowest element.
    • 배열에서 가장 높은 element와 가장 낮은 element를 제외하고 모든 숫자를 합한다.
  • If array is empty, null or None, or if only 1 element exists, return 0.
    • 배열이 비어 있거나, null이거나, 1개의 element만 있는 경우 0을 반환한다.



Solution 01

function sumWithoutMaxAndMin(arr) {
  if (!arr || arr.length < 3) return 0;
  
  let result = 0;
  let max = arr[0];
  let min = arr[0];
  
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] > max) {
      max = arr[i];
    }
    
    if (arr[i] < min) {
      min = arr[i];
    }
    
    result += arr[i];
  }
  
  return result - max - min;
}

sumWithoutMaxAndMin([]);            // 0
sumWithoutMaxAndMin([1]);           // 0
sumWithoutMaxAndMin([1, 2]);        // 0
sumWithoutMaxAndMin([1, 2, 3]);     // 2
sumWithoutMaxAndMin([1, 2, 3, 4]);  // 5 (2 + 3)
sumWithoutMaxAndMin([2, 4, 1, 3]);  // 5 (2 + 3)
sumWithoutMaxAndMin([5, 6, 7, 8]);  // 13 (6 + 7)
sumWithoutMaxAndMin([8, 5, 7, 6]);  // 13 (6 + 7)


Solution 02

function sumWithoutMaxAndMin(arr) {
  if (!arr || arr.length < 3) return 0;
  
  let result = 0;
  let max = min = arr[0];
  
  for (let i = 0; i < arr.length; i++) {
    arr[i] > max ? (max = arr[i]) : arr[i] < min ? (min = arr[i]) : arr[i];
    result += arr[i];
  }
  
  return result - max - min;
}

sumWithoutMaxAndMin([]);            // 0
sumWithoutMaxAndMin([1]);           // 0
sumWithoutMaxAndMin([1, 2]);        // 0
sumWithoutMaxAndMin([1, 2, 3]);     // 2
sumWithoutMaxAndMin([1, 2, 3, 4]);  // 5 (2 + 3)
sumWithoutMaxAndMin([2, 4, 1, 3]);  // 5 (2 + 3)
sumWithoutMaxAndMin([5, 6, 7, 8]);  // 13 (6 + 7)
sumWithoutMaxAndMin([8, 5, 7, 6]);  // 13 (6 + 7)


Solution 03

function sumWithoutMaxAndMin(arr) {
  if (!arr || arr.length < 3) return 0;
  
  let sorted = arr.sort((a, b) => a - b);
  let result = 0;
  
  for (let i = 1; i < sorted.length - 1; i++) {
    result += sorted[i];
  }
  
  return result;
}

sumWithoutMaxAndMin([]);            // 0
sumWithoutMaxAndMin([1]);           // 0
sumWithoutMaxAndMin([1, 2]);        // 0
sumWithoutMaxAndMin([1, 2, 3]);     // 2
sumWithoutMaxAndMin([1, 2, 3, 4]);  // 5 (2 + 3)
sumWithoutMaxAndMin([2, 4, 1, 3]);  // 5 (2 + 3)
sumWithoutMaxAndMin([5, 6, 7, 8]);  // 13 (6 + 7)
sumWithoutMaxAndMin([8, 5, 7, 6]);  // 13 (6 + 7)


Solution 04

function sumWithoutMaxAndMin(arr) {
  return arr ? arr.sort((a, b) => a - b).slice(1, -1).reduce((result, i) => result + i, 0) : 0;
}

sumWithoutMaxAndMin([]);            // 0
sumWithoutMaxAndMin([1]);           // 0
sumWithoutMaxAndMin([1, 2]);        // 0
sumWithoutMaxAndMin([1, 2, 3]);     // 2
sumWithoutMaxAndMin([1, 2, 3, 4]);  // 5 (2 + 3)
sumWithoutMaxAndMin([2, 4, 1, 3]);  // 5 (2 + 3)
sumWithoutMaxAndMin([5, 6, 7, 8]);  // 13 (6 + 7)
sumWithoutMaxAndMin([8, 5, 7, 6]);  // 13 (6 + 7)