티스토리 뷰
간단하게는 minimum value 로 each index를 subtract할 수 있는 갯수를 구하는 문제.
Solution 1 in Javascript
const arr = [5, 3, 2, 2, 2, 8]
function cutTheSticks(arr) {
//sort the array
let sorted = arr.sort();
//set index[0] to a min
let min = sorted[0];
console.log(sorted.length);
for (let i = 0; i < sorted.length; i++) {
if (sorted[i] > min) {
min = sorted[i]; //change min to next shortest min
console.log(sorted.length - i);
}
}
}
cutTheSticks(arr); //6 3 2 1
solution
1. array 를 sort한다.
2. first index를 min 으로 지정
3. 전체 index를 loop
4. sorted[i] > min condition 이 duplicate index 가 몇개가 있던지간에 다음 큰 수가 있는 index number which is 'i' 로 넘어가게 한다.
5. sorted.length - i 를 print 함으로써 남아있는 초의 갯수를 알 수 있다.
이 solution은 굳이 each candle을 subtract하지 않고 풀었다.
Solution 2 in Javascript
const arr = [5, 3, 2, 2, 2, 8]
function cutTheSticks(arr) {
let newArr = [...arr]; //spread operator
const result = [newArr.length]; //to print the length first
while (newArr.length > 0) {
let min = Math.min(...newArr); //spread operator
//accumulator, currentValue
newArr = newArr.reduce((target, stick) => {
stick > min && target.push(stick - min); //short circuit evaluation
return target;
}, []); //accumulator is [] here
newArr.length > 0 && result.push(newArr.length);
}
console.log(result);
}
cutTheSticks(arr); //[6, 3, 2, 1]
이 solution은 each candle 을 min value만큼 뺀 수를 push 했다.
Solution 3 in Javascript
Reference
www.hackerrank.com/challenges/cut-the-sticks/problem
Cut the sticks | HackerRank
Given the lengths of n sticks, print the number of sticks that are left before each cut operation.
www.hackerrank.com
'Algorithms' 카테고리의 다른 글
CamelCase (0) | 2021.02.12 |
---|---|
smallest distance (0) | 2021.01.16 |
Equalize the Array (0) | 2020.12.11 |
Invert Binary Tree (0) | 2020.11.30 |
Sequence Equation (0) | 2020.10.30 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- compareTo()
- java
- javascript
- 알고리즘
- math.abs
- substring()
- 프로그래머스 알고리즘
- spring boot application
- easy javascript algorithm
- rest parameter
- hackerrank solution
- easy algorithm
- Javascript Algorithm
- repeat()
- hackerrank javascript solution
- Object type casting
- algorithm
- equals()
- Collection Framework
- math.max
- string class in java
- hackerrank javascript
- C++
- HashMap
- 프로그래머스 알고리즘문제
- ... in Javascript
- hackerrank
- 프로그래머스
- code refactoring
- HackerRank Algorithm
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 | 29 |
30 | 31 |
글 보관함