Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 23131

Split array of integers into subarrays with the biggest difference between min and max

$
0
0

I'm trying to find the algorithm efficiently solving this problem:

Given an unsorted array of numbers, you need to divide it into several subarrays of length from a to b, so that the sum of differences between the minimum and maximum numbers in each of the subarrays is the greatest. The order of the numbers must be preserved.

Examples:

a = 3, b = 7input: [5, 8, 4, 5, 1, 3, 5, 1, 3, 1]answer: [[5, 8, 4], [5, 1, 3], [5, 1, 3, 1]] (diff sum is 12)a = 3, b = 4input: [1, 6, 2, 2, 5, 2, 8, 1, 5, 6]answer: [[1, 6, 2], [2, 5, 2, 8], [1, 5, 6]] (diff sum is 16)a = 4, b = 5input: [5, 8, 4, 5, 1, 3, 5, 1, 3, 1, 2]answer: splitting is impossible

The only solution I've come up with so far is trying all of the possible subarray combinations.

from collections import dequedef partition_array(numbers, min_len, max_len):  max_diff_subarray = None  queue = deque()  for end in range(min_len - 1, max_len):    if end < len(numbers):      diff = max(numbers[0:end + 1]) - min(numbers[0:end + 1])      queue.append(Subarray(previous=None, start=0, end=end, diff_sum=diff))  while queue:    subarray = queue.popleft()    if subarray.end == len(numbers) - 1:      if max_diff_subarray is None:        max_diff_subarray = subarray      elif max_diff_subarray.diff_sum < subarray.diff_sum:        max_diff_subarray = subarray      continue    start = subarray.end + 1    for end in range(start + min_len - 1, start + max_len):      if end < len(numbers):        diff = max(numbers[start:end + 1]) - min(numbers[start:end + 1])        queue.append(Subarray(previous=subarray, start=start, end=end, diff_sum=subarray.diff_sum + diff))      else:        break  return max_diff_subarrayclass Subarray:  def __init__(self, previous=None, start=0, end=0, diff_sum=0):    self.previous = previous    self.start = start    self.end = end    self.diff_sum = diff_sumnumbers = [5, 8, 4, 5, 1, 3, 5, 1, 3, 1]a = 3b = 7result = partition_array(numbers, a, b)print(result.diff_sum)

Are there any more time efficient solutions?


Viewing all articles
Browse latest Browse all 23131

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>