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' represents its 'power'. The array will be evaluated as 'valid' if the length of the array is greater than two and the first and last values of the array are equal. We have to make the array valid by deleting elements from the array so that the remaining elements satisfy the condition. As output, we return the maximum possible power value by adding all the power values of the valid 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 is 4 + 5 + 3 + 4 = 16. This is the maximum possible sum for any valid array from the given input.

Approach

To solve this, we will follow these steps −

  • table := a new map to store first and last occurrence of each value

  • prefix := a new list initialized with value 0 for prefix sums

  • negative := a new list initialized with value 0 for negative value tracking

  • 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 (update last occurrence)

    • add a new element to prefix that equals 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 (meaning we found matching start and end), then

      • sm1 := prefix[j+1] - prefix[i] (total sum in range)

      • 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.append(prefix[-1] + j)
        negative.append(negative[-1])
        
        if j < 0:
            negative[-1] += j

    ans = float('-inf')
    
    for i, j in table.values():
        if j != 0:  # We found matching start and end positions
            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

# Test with the example
nums = [3, 4, 5, 3, 4]
result = solve(nums)
print(f"Input: {nums}")
print(f"Output: {result}")

The output of the above code is −

Input: [3, 4, 5, 3, 4]
Output: 16

How It Works

The algorithm works by:

  • Tracking the first and last occurrence of each value in the array

  • Using prefix sums to quickly calculate the sum of any subarray

  • Handling negative values separately to maximize the result

  • For each value that appears at least twice, calculating the maximum sum of a valid subarray that starts and ends with that value

Another Example

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.append(prefix[-1] + j)
        negative.append(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

# Test with different examples
test_cases = [
    [1, 2, 3, 1],
    [2, -1, -2, 2],
    [5, 1, 3, 5, 2]
]

for test in test_cases:
    result = solve(test)
    print(f"Input: {test}, Output: {result}")

The output of the above code is −

Input: [1, 2, 3, 1], Output: 7
Input: [2, -1, -2, 2], Output: 6
Input: [5, 1, 3, 5, 2], Output: 14

Conclusion

This algorithm efficiently finds the maximum sum of a valid subarray by using prefix sums and tracking negative values separately. The time complexity is O(n) where n is the length of the input array, making it an optimal solution for this problem.

Updated on: 2026-03-26T14:47:49+05:30

295 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements