forked from behappyyoung/javascriptsamplecodes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFind_Max_j-i_From_Array.js
More file actions
61 lines (47 loc) · 1.72 KB
/
Copy pathFind_Max_j-i_From_Array.js
File metadata and controls
61 lines (47 loc) · 1.72 KB
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/**
* Created by young on 2/27/15.
*/
function firstSolution(myArray){
var step=0;
var max = 0;
for(var i=0; i< myArray.length-1; i++){
for(var j=myArray.length-1; j > i ; j--){
var inmax = myArray[j]-myArray[i];
max = (max < inmax)? inmax : max;
printText += ++step + '/' + myArray[j] +'-' +myArray[i] +' :'+max + '<br />';
}
}
return max;
}
function secondSolution(myArray){
var length = myArray.length;
var max= 0, step=0;
//create min array
var MinArray=[];
MinArray[0] = myArray[0];
for(var i=1; i<length; i++){
MinArray[i] = (myArray[i] < MinArray[i-1])? myArray[i] : MinArray[i-1];
printText += ++step + ' / ';
}
//create max array
var MaxArray=[];
MaxArray[length-1] = myArray[length-1];
for(var j= length-2; j >= 0 ; j--){
MaxArray[j] = (myArray[j] > MaxArray[j+1])? myArray[j] : MaxArray[j+1];
printText += ++step + '/ ';
}
for(i=0; i<length; i++){
var inmax = MaxArray[i]-MinArray[i];
max = (max < inmax)? inmax : max;
printText += ++step + '| ';
}
printText += '<br /> MinArray : '+ MinArray.toString() +' / MaxArray : ' + MaxArray.toString()+ '<br />';
return max;
}
var testArray = [4, 50, 10, 30,60, 7, 8, 1, 44, 9, 15, 20, 33, 55];
var printText=' Test Array : [ ' + testArray.toString() + ' ]<br /> steps : <br />';
var result = firstSolution(testArray);
document.getElementById('solution1').innerHTML = printText + ' result : ' + result;
printText=' Test Array : [ ' + testArray.toString() + ' ]<br /> steps : <br />';
result = secondSolution(testArray);
document.getElementById('solution2').innerHTML = printText + ' result : ' + result;