Iam_Sandeep

subarray with given sum

Nov 9th, 2021
1,011
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.09 KB | None | 0 0
  1. #User function Template for python3
  2.  
  3. #Function to find a continuous sub-array which adds up to a given number.
  4. class Solution:
  5.     def subArraySum(self,arr, n, s):
  6.         l,r,sum=0,1,arr[0]
  7.         while r<=n:
  8.             while sum>s:
  9.                 sum-=arr[l]
  10.                 l+=1
  11.             if sum==s:
  12.                 return [l+1,r]
  13.                 break
  14.             else:
  15.                 if r<n:
  16.                     sum+=arr[r]
  17.             r+=1
  18.         if r>n:
  19.             return [-1]
  20.            
  21.        
  22.  
  23. #{
  24. #  Driver Code Starts
  25. #Initial Template for Python 3
  26.  
  27. import math
  28.  
  29. def main():
  30.         T=int(input())
  31.         while(T>0):
  32.            
  33.             NS=input().strip().split()
  34.             N=int(NS[0])
  35.             S=int(NS[1])
  36.            
  37.             A=list(map(int,input().split()))
  38.             ob=Solution()
  39.             ans=ob.subArraySum(A, N, S)
  40.            
  41.             for i in ans:
  42.                 print(i, end=" ")
  43.                
  44.             print()
  45.            
  46.             T-=1
  47.  
  48.  
  49. if __name__ == "__main__":
  50.     main()
  51. # } Driver Code Ends
Advertisement
Add Comment
Please, Sign In to add comment