티스토리 뷰
1. Initialize random index for minimum and maximum value. Anyhow it's gonna be updated.
2. To find the max and min element in an array, use Max and Min function.
Example Code in Java
public class Main{
public static void main(String args[]) {
int arr[] = {2,4,3,7,5};
System.out.println(getMinMax(arr));
}
public static int getMinMax(int[] arr) {
//just set arbitrary index 0,1 for now
int min = arr[0];
int max = arr[1] - arr[0];
for (int i = 1; i < arr.length; i++) {
int current = arr[i];
int largestNum = current - min;
max = Math.max(max, largestNum);
min = Math.min(min, current);
}
return max;
}
}
|
Output
5
Example code in JavaScript #1
const arr = [2,4,3,7,5];
function main(arr) {
const sortArray = arr.sort();
let leng = arr.length;
let min = sortArray[0];
let max = sortArray[leng-1];
console.log(max - min);
}
main(arr);
Example code in JavaScript #2
const arr = [2, 4, 3, 7, 5];
function main(arr) {
const sortArray = arr.sort();
let leng = arr.length;
let max = sortArray[leng - 1];
let result = sortArray.slice(0, max).reduce((a, b) => b - a)
console.log(result);
}
main(arr);
'Algorithms' 카테고리의 다른 글
Plus Minus (0) | 2020.07.29 |
---|---|
Diagonal Difference in JavaScript (0) | 2020.07.27 |
Get the second smallest element in array (0) | 2019.09.07 |
Counting Valley (0) | 2019.08.31 |
Comparison performing contains() for ArrayList and HashSet (0) | 2019.08.31 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- spring boot application
- 프로그래머스 알고리즘
- string class in java
- compareTo()
- hackerrank javascript
- hackerrank javascript solution
- rest parameter
- equals()
- 프로그래머스
- code refactoring
- java
- HackerRank Algorithm
- Javascript Algorithm
- hackerrank
- C++
- substring()
- easy algorithm
- repeat()
- 알고리즘
- math.abs
- Object type casting
- algorithm
- math.max
- ... in Javascript
- javascript
- 프로그래머스 알고리즘문제
- Collection Framework
- hackerrank solution
- HashMap
- easy javascript 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 |
글 보관함