Advertisement
makispaiktis

DCP18 - Max of Subarrays

Sep 6th, 2020 (edited)
1,505
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.46 KB | None | 0 0
  1. '''
  2. This problem was asked by Google.
  3. Given an array of integers and a number k, where 1 <= k <= length of the array, compute the maximum values of each subarray of length k.
  4. For example, given array = [10, 5, 2, 7, 8, 7] and k = 3, we should get: [10, 7, 8, 8], since:
  5. 10 = max(10, 5, 2)
  6. 7 = max(5, 2, 7)
  7. 8 = max(2, 7, 8)
  8. 8 = max(7, 8, 7)
  9. Do this in O(n) time and O(k) space.
  10. '''
  11.  
  12. def maxOfSubarrays(arr, k):
  13.     if k <= 0 or k > len(arr) or k != int(k):
  14.         return "Error using function maxOfSubarrays"
  15.     subArrays = list()
  16.     for i in range(len(arr) + 1 - k):
  17.         subArray = list()
  18.         for j in range(k):
  19.             subArray.append(arr[i+j])
  20.         subArrays.append(subArray)
  21.     # Now, the list subArrays contains all the subArrays of length k given the array "arr"
  22.     maxes = list()
  23.     for sub in subArrays:
  24.         maxes.append(max(sub))
  25.     return subArrays, maxes
  26.  
  27. def prettyPrint(arr, k):
  28.     print("*****************************************************")
  29.     print("Array = " + str(arr) + ", k = " + str(k))
  30.     subArrays, maxes = maxOfSubarrays(arr, k)
  31.     for i in range(len(subArrays)):
  32.         print("SubArray = " + str(subArrays[i]) + " ----> Max = " + str(maxes[i]))
  33.     print("Maxes = " + str(maxes))
  34.     print("*****************************************************")
  35.     print()
  36.  
  37. # MAIN FUNCTION
  38. arr1 = [10, 5, 2, 7, 8, 7]
  39. k1 = 3
  40. arr2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  41. k2 = 5
  42. prettyPrint(arr1, k1)
  43. prettyPrint(arr2, k2)
  44.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement