**Prerequisite:** Segment Trees, Lazy Propagation in Segment Tree.

Given an array **arr[]** of **N** integers. The task is to do the following operations:

- Change the value
**arr[i]**to**min(arr[i], X)**where X is an integer for a given range**[L, R]**. - Find the maximum value from index
**L to R**where**0 ≤ L ≤ R ≤ N-1**before and after the update given to the array above. - Find the sum of the element from index
**L to R**where**0 ≤ L ≤ R ≤ N-1**before and after the update given to the array above.

**Examples:**

```
Input: arr[] = {1, 2, 3, 4, 5}, L = 2, R = 4, X = 3
Output:
Maximum in range [2, 4] before update: 5
Sum in range [2, 4] before update: 12
Maximum in range [2, 4] after update: 3
Sum in range [2, 4] after update: 9
Explanation:
Before Update:
arr[] = {1, 2, 3, 4, 5}
The maximum value from [L, R] is 5
Sum in range [L, R] is 3 + 4 + 5 = 12
After Update:
arr[] = {1, 2, 3, 3, 3}
The maximum value from [L, R] is 3
Sum in range [L, R] is 3 + 3 + 3 = 9
Input: arr[] = {1, 4, 19, 0, 7, 22, 7}, L = 1, R = 5, X = 14
Output:
Maximum in range [1, 5] before update: 22
Sum in range [1, 5] before update: 52
Maximum in range [1, 5] after update: 22
Sum in range [1, 5] after update: 39
Explanation:
Before Update:
arr[] = {1, 4, 19, 0, 7, 22, 7}
The maximum value from [L, R] is 22
Sum in range [L, R] is 4 + 19 + 0 + 7 + 22 = 52
After Update:
arr[] = {1, 4, 14, 0, 7, 14, 7}
The maximum value from [L, R] is 14
Sum in range [L, R] is 4 + 14 + 0 + 7 + 14 = 39
```

**Approach:**

**pushdown():**The lazy tag is applied to current node and then is pushed down to its children.**tag_condition:**It is the condition that needs to be satisfied to set the lazy node. In normal lazy trees, it is generally the condition that ranges of the node covers lie entirely in the update range.- A node in the segment tree represents a range of the array. Now all elements in that range will have different values and they will change by different amounts during an update. So we need the information about distinct values and their counts in that range. So this becomes a worst-case O**(N)** operation as at max
**N**distinct nodes in a range. - Below is the approach to solve these restrictions in Segment Tree. Each node in the Segment Tree will have the following values:

**value**: The value of a range, here sum of all elements in that range**maxval**: Maximum value in that range**secondmax**: Strict second maximum value in that range**cnt_max**: Count of maximum value in that range**cnt_secondmax**: Count of secondmax in that range

#advanced data structure #algorithms #arrays #competitive programming #recursion #tree #array-range-queries #segment-tree

1.40 GEEK