<script>
function
getMid(s,e)
{
return
Math.floor(s + (e - s) / 2);
}
function
MaxUtil(st,ss,se,l,r,node)
{
if
(l <= ss && r >= se)
return
st[node];
if
(se < l || ss > r)
return
-1;
let mid = getMid(ss, se);
return
Math.max(
MaxUtil(st, ss, mid, l, r,
2 * node + 1),
MaxUtil(st, mid + 1, se, l, r,
2 * node + 2));
}
function
updateValue(arr,st,ss,se,index,value,node)
{
if
(index < ss || index > se) {
document.write(
"Invalid Input<br>"
);
return
;
}
if
(ss == se) {
arr[index] = value;
st[node] = value;
}
else
{
let mid = getMid(ss, se);
if
(index >= ss && index <= mid)
updateValue(arr, st, ss, mid,
index, value,
2 * node + 1);
else
updateValue(arr, st, mid + 1, se, index,
value, 2 * node + 2);
st[node] = Math.max(st[2 * node + 1],
st[2 * node + 2]);
}
return
;
}
function
getMax(st,n,l,r)
{
if
(l < 0 || r > n - 1 || l > r) {
document.write(
"Invalid Input<br>"
);
return
-1;
}
return
MaxUtil(st, 0, n - 1, l, r, 0);
}
function
constructSTUtil(arr,ss,se,st,si)
{
if
(ss == se) {
st[si] = arr[ss];
return
arr[ss];
}
let mid = getMid(ss, se);
st[si] = Math.max(
constructSTUtil(arr, ss, mid,
st, si * 2 + 1),
constructSTUtil(arr, mid + 1,
se, st,
si * 2 + 2));
return
st[si];
}
function
constructST(arr,n)
{
let x = Math.floor(Math.ceil(Math.log(n) / Math.log(2)));
let max_size = 2 * Math.floor(Math.pow(2, x)) - 1;
let st =
new
Array(max_size);
constructSTUtil(arr, 0, n - 1, st, 0);
return
st;
}
let arr=[ 1, 3, 5, 7, 9, 11];
let n = arr.length;
let st = constructST(arr, n);
document.write(
"Max of values in given range = "
+ getMax(st, n, 1, 3)+
"<br>"
);
updateValue(arr, st, 0, n - 1, 1, 8, 0);
document.write(
"Updated max of values in given range = "
+ getMax(st, n, 1, 3)+
"<br>"
);
</script>