Guys i'm working through a program to find the largest Number in an negative array.What would be the best algorithm for this.
ex:
[-72, -3, -17, -10]
Asked
Active
Viewed 3,361 times
-4

rocktimsaikia
- 137
- 4
- 10
-
1What is your expected output ? – Mihai Alexandru-Ionut May 14 '18 at 09:00
-
4please show *the not so best* algorithm first. – Nina Scholz May 14 '18 at 09:00
-
1it's not different from the case where all the numbers are positive. what problem are you having exactly? – Federico klez Culloca May 14 '18 at 09:00
-
2Please explain "largest negative number"? Do you mean `-3` or `-72`? – evolutionxbox May 14 '18 at 09:03
-
Possible duplicate of [Find the min/max element of an Array in JavaScript](https://stackoverflow.com/questions/1669190/find-the-min-max-element-of-an-array-in-javascript) – Narendra Jadhav May 14 '18 at 09:03
2 Answers
4
You can use Math.max
method and spread
syntax.
array = [-72, -3, -17, -10]
console.log(Math.max(...array));

Mihai Alexandru-Ionut
- 47,092
- 13
- 101
- 128
-
In my mind the term "largest negative number" is ambiguous... I don't know if the OP meant `-3` or `-72`. (Not that it changes your code much) – evolutionxbox May 14 '18 at 09:04
-
-
-
0
var array = [-72, -3, -17, -10];
var lg = array[0];
var sm = array[0];
for (var i = 1; i < array.length; i++) {
if (array[i] > lg) {
lg = array[i];
} else if(array[i] < sm) {
sm = array[i];
}
}
console.log('largest No :' + lg);
console.log('smallest No :' + sm);

vicky patel
- 699
- 2
- 8
- 14