-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstock_best_deal.html
More file actions
83 lines (68 loc) · 1.81 KB
/
stock_best_deal.html
File metadata and controls
83 lines (68 loc) · 1.81 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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<script type="text/javascript">
// given a array of changing price
var stockFlow = [ 6, 4, 6, 5, 9, 7, 6, 12, 2, 6, 11, 2, 4 ];
// 2 4 6. 4. 5. 2
// helper function that looking for max number in array
function findMax(arr){
var max = arr[0], index = 0;
for( var i = 1; i < arr.length; i++ ){
if( max < arr[i] ){
max = arr[i];
index = i;
}
}
return { max: max, index: index }
}
// console.log( "finding max" );
// console.log( findMax(stockFlow) );
console.log( "given an stock flow:" );
console.log( stockFlow );
// finding best deal
function best(arr){
var maxpforit = -999, buy = 0, sell = 0;
for ( var i = 0; i < arr.length; i++ ) {
var result = findMax( arr.slice(i+1, arr.length-1) );
if( maxpforit < (result.max - arr[i]) ){
maxpforit = result.max - arr[i];
buy = i;
sell = result.index + i + 1;
}
}
return {maxProfit: maxpforit, buytime: buy, selltime: sell}
}
console.log( "best deal" );
console.log( best(stockFlow) );
stockFlow = [ 6, 4, 6, 5, 9, 7, 6, 12, 2, 6, 11, 2, 4 ];
// 2 4 6. 4. 5. 2
// making best deals
function profitMaker(arr){
var profit = 0, i = 0;
while ( arr[ i + 1 ] > arr[ i ] ){
profit += arr[i+1] - arr[i];
i++;
}
return {profit: profit, i: i}
}
// all best deals from flow stock
function allBestDeals(arr){
var allProfit = 0;
var result;
for (var i = 0; i < arr.length; i++){
result = profitMaker(arr.slice(i, arr.length));
allProfit += result.profit;
i += result.i;
}
return allProfit
}
console.log( "all best deals from flow stock:" );
console.log( allBestDeals(stockFlow) );
</script>
</body>
</html>