# Merging adjacent polygons with aggregated sum beeing inside a certain range

## The data

I have a polygon layer with polygons (download the data here) of different sizes as can be seen on the screenshot. Each polygon contains a value for the attribute called `count`. The range of these values is from 1 to 997.

## What I want to do

Using QGIS 3.24 or later, I want to merge adjacent polygons in a way to create contiguous polygons (of any shape, not necessarily rectangles - but still as compact as possible) with the aggregated sum of the merged polygons being at least of value 500, but in no case be larger then 1000.

## The question

How do I merge polygons in a way to get an accumalted sum of between 500 and 1000 for each resulting polygon?

## What I tried

This is a follow up question. See here for context.

## Example

For example: on the upper right (see screenshot below), there is a polygon with value 51; it could be merged with the polygon to its upper left (12): 51+12=63. It can't be, however, merged with the polygon 983, as the sum would be too large (51+983 > 1000). However, to met the condition that the sum should be > 500, polygon 51 could be merged with two other ones at the left: 146 and 387, thus: 51+12+146+387 = 596 : this is larger than 500 and smaller than 1000.

## Conditions

Like this, adjacent polygons should be merged to come as close to the conditions I defined as possible. I am aware that an exact solution probably does not exist and I do not really need a solution to meet 100% of the conditions - but as close as possible with reasonable effort. The conditions in decreasing importance:

• aggregeate sum of merged polygons being min. 500
• aggregeate sum of merged polygons being max. 1000
• shapes should be as compact as possible, square shapes prefered (avoiding "gerrymandering" style polygons as much as possible)

Screenshot: polygons are in graduated style, for lower values in white, higher values in red: