Program to find out the maximum value of a 'valid' array in Python


Suppose, we have an array of n integers 'nums'. Each value in 'nums' represent its 'power'. The array will be evaluated 'valid' if the length of the array is greater than two and the first and last value of the array is equal. We have to make the array valid by deleting elements from the array so that the rest can satisfy the condition. As output, we return the maximum possible power value of the array by adding all the power values of the array.

So, if the input is like nums = [3, 4, 5, 3, 4], then the output will be 16.

If we remove the first value 3 from the array nums, then it becomes [4, 5, 3, 4]. This is a valid array and the sum of the powers are 4 + 5 + 3 + 4 = 16. This is the maximum possible sum for any valid array from the given input.

To solve this, we will follow these steps −

  • table := a new map

  • prefix := a new list initialized with value 0

  • negative := a new list initialized with value 0

  • for each index i and value j in nums, do

    • if j is not present in table, then

      • table[j] := a new pair (i, 0)

      • otherwise,

        • table[j, -1] := i

      • add a new element to prefix that is equal to the last element of prefix + j

      • duplicate the last element of negative

      • if j < 0 , then

        • last element of negative := last element of negative + j

  • ans := negative infinity

  • for each pair (i,j) in all values of table, do

    • if j is not same as 0, then

      • sm1 := prefix[j+1] - prefix[i]

      • if j > i+1, then

        • sm2 := negative[j] - negative[i+1]

      • otherwise,

        • sm2 := 0

      • ans := maximum of (ans, sm1 - sm2)

  • return ans

Example

Let us see the following implementation to get better understanding −

def solve(nums):
   table = {}
   prefix = [0]
   negative = [0]
   for i, j in enumerate(nums):
      if j not in table:
         table[j] = [i, 0]
      else:
         table[j][-1] = i
      prefix += prefix[-1] + j,
      negative += negative[-1],
      if j < 0:
         negative[-1] += j

   ans = float('-inf')
   for i,j in table.values():
      if j != 0:
         sm1 = prefix[j+1] - prefix[i]
         sm2 = negative[j] - negative[i+1] if j > i+1 else 0
         ans = max(ans, sm1 - sm2)
   return ans

print(solve([3, 4, 5, 3, 4]))

Input

[3, 4, 5, 3, 4]

Output

16

Updated on: 08-Oct-2021

167 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements