I have used the segment to optimize the time complexity (for updation purpose and also for the query purpose)
you can learn about segment tree from here
Segment Tree - Algorithms for Competitive Programming
4 flowers
n = 4
4
3 1 4 2
10 20 30 40
data = [flower height, flower beauty value, index]
flowers = [[3, 10, 1], [1, 20 , 2], [4, 30, 3], [2, 40, 4]]
sort these flowers on the basis of the height (means on the basis of data[0] )
sorted data
flowers = [[4, 30, 3], [3, 10, 1], [2, 40, 4], [1, 20, 2]]
we will iterate over all the flower, try to find out what is maximum value of the beauties we can have as a sequence such that the current flower’s height is least in that sequence
answer = [0, 0, 0, 0] => that will stored our current maximum beauties, which are zeros initially
iterate over flowers:
flower1:
[4, 30, 3]
we will check for index [3 , n] what is the maximum beauty value which is 0
beauty = 30 + 0
update the answer list with beauty 30 at index 3
answer = [0, 0, 30, 0]
flower2:
[3 ,10, 1]
we will check for index [1 , n] what is the maximum beauty value which is 30
beauty = 30 + 10 = 40
update the answer list with beauty 40 at index 1
answer = [40, 0, 30, 0]
flower3:
[2 ,40, 4]
we will check for index [4 , n] what is the maximum beauty value which is 0
beauty = 40 + 0 = 40
update the answer list with beauty 40 at index 4
answer = [40, 0, 30, 40]
flower4:
[1 ,20, 2]
we will check for index [2 , n] what is the maximum beauty value which is 40
beauty = 40 + 20 = 60
update the answer list with beauty 40 at index 4
answer = [40, 60, 30, 40]
answer = [40, 60, 30, 40]
maximum value is 60