How can i reduce the Time Complexity of this?


#1

def solve(self, A, B):
s = 0
for i in range(len(A)-B+1):
l = A[i:i+B]
s = s + min(l)+ max(l)
return s%(10**9 + 7)


#2
from collections import deque 

class Solution:
    def solve(self, arr, k):
        Sum = 0
        n = len(arr)
        S = deque()
        G = deque()
    
        for i in range(k):
            while ( len(S) > 0 and arr[S[-1]] >= arr[i]): 
                S.pop() # Remove from rear 
            while ( len(G) > 0 and arr[G[-1]] <= arr[i]): 
                G.pop() # Remove from rear 
    
            G.append(i)
            S.append(i)
    
        for i in range(k, n):
            Sum += arr[S[0]] + arr[G[0]] 
            while ( len(S) > 0 and S[0] <= i - k): 
                S.popleft() 
            while ( len(G) > 0 and G[0] <= i - k): 
                G.popleft() 
            while ( len(S) > 0 and arr[S[-1]] >= arr[i]): 
                S.pop() # Remove from rear 
            while ( len(G) > 0 and arr[G[-1]] <= arr[i]): 
                G.pop() # Remove from rear 
            G.append(i) 
            S.append(i)
            
        Sum += arr[S[0]] + arr[G[0]]
        return Sum % 1000000007