# Highest order to maximize the worth

Given, an array arr[] of N integers, the duty is to make a choice some integers from this array arr[] and prepare them in every other array brr[], such that the sum of brr[i]*(i+1) for each and every index in array brr is most. To find out the utmost imaginable such worth for a given array arr.

Enter: N = 5, arr[] = {-1, -8, 0, 5, -9}
Output: 14
Rationalization: Through deciding on -1, 0, and 5 we can get the utmost imaginable worth.(-1*1 + 0*2 + 5*3 = 14)

Enter: N = 3, arr[] = {-1, -8, -9}
Output: 0
Rationalization: Since the entire numbers are adverse itâs higher no longer to make a choice any quantity.

Way: To resolve the issue observe the beneath thought:

The issue can also be solved the usage of a grasping manner. The instinct at the back of the grasping manner is that the utmost worth is bought via deciding on the most important quantity first, and the smallest quantity remaining. Through sorting the array in reducing order, we will be able to make certain that we now have the most important quantity to start with, and thus maximize the worth.

Steps that had been to observe the above manner:

• First, we type the enter array in reducing order.Â
• Then, we iterate over the array and calculate the prefix sums of the weather, including each and every prefix sum to the outcome so long as it stays non-negative.Â
• If the prefix sum turns into adverse at any level, we prevent the iteration and go back the present outcome.
• Through preventing the iteration as quickly because the prefix sum turns into adverse, we will be able to make certain that we donât make a selection any numbers that experience a web adverse contribution to the entire worth. This permits us to acquire the utmost worth.

Underneath is the code to put in force the above manner:

## Python3

 `def` `bestOrder(arr, N):` `Â `Â  `Â Â Â Â Â Â Â Â ` `Â Â Â Â ` `Â Â Â Â ``arr.type(opposite ``=` `True``)` `Â `Â  `Â Â Â Â ` `Â Â Â Â ` `Â Â Â Â ``prefixsum, outcome ``=` `0``, ``0` `Â `Â  `Â Â Â Â ` `Â Â Â Â ` `Â Â Â Â ``for` `i ``in` `vary``(N):` `Â `Â  `Â Â Â Â Â Â ` `Â Â Â Â Â Â Â Â ``prefixsum ``+``=` `arr[i]` `Â `Â  `Â Â Â Â Â Â ` `Â Â Â Â Â Â ` `Â Â Â Â Â Â Â Â ``if` `prefixsum < ``0``:` `Â Â Â Â Â Â Â Â Â Â Â Â ``ruin` `Â Â Â Â Â Â ` `Â Â Â Â Â Â ` `Â Â Â Â Â Â Â Â ``outcome ``+``=` `prefixsum` `Â Â Â Â ``go back` `outcome` `Â `Â  `Â `Â  `N ``=` `5` `arr ``=` `[``-``1``, ``-``8``, ``0``, ``5``, ``-``9``]` `Â `Â  `print``(bestOrder(arr, N))`

Time Complexity: O(N*logN), the place N is the period of the array.
Auxiliary Area: O(1), as we aren’t the usage of any more space.