907. Sum of Subarray Minimums

Given an array of integers arr, find the sum of min(b), where b ranges over every (contiguous) subarray of arr. Since the answer may be large, return the answer modulo 109 + 7.

 Example:

Input: arr = [3,1,2,4]
Output: 17
Explanation: 
Subarrays are [3], [1], [2], [4], [3,1], [1,2], [2,4], [3,1,2], [1,2,4], [3,1,2,4]. 
Minimums are 3, 1, 2, 4, 1, 1, 2, 1, 1, 1. Sum is 17.

def sumSubarrayMins(self, arr: List[int]):
       
    L = len(arr), total = 0, M = (10**9 + 7)
   
    left =  [i+1 for i in range(L)]
    right = [L-i for i in range(L)]
   
    p = [], n = []
   
    for i in range(L):
       
        while p:                
            if p[-1][0] <= arr[i]:
                break
            else:
                p.pop()
        if not p:                
            left[i] = i+1
        else:            
            left[i] = i-p[-1][1]
           
        p.append((arr[i], i))
           
        # For right side, the numbers being poppped out
        # are the ones that is getting their right[] array
        # filled.
        #            
        while n:                
            if n[-1][0] <= arr[i]:
                break
            else:
                x = n[-1][1]
                right[x] = i - x
                n.pop()
               
        n.append((arr[i], i))
   
    for i,e in enumerate(arr):
        total = total + e * left[i]*right[i]
   
    return total % M

Comments

Popular posts from this blog

849. Maximize Distance to Closest Person

347. Top K Frequent Elements

139. Word Break