python等和子数组最小和
时间: 2024-06-14 13:06:51 浏览: 56
华为OD机试 - 等和子数组最小和(Java & JS & Python & C & C++).html
根据提供的引用内容,有两个问题涉及到了子数组的最小和。下面是两种不同的方法来解决这个问题:
方法一:动态规划
```python
def minSum(nums):
n = len(nums)
total_sum = sum(nums)
target_sum = total_sum // 2
dp = [[False] * (target_sum + 1) for _ in range(n + 1)]
dp[0][0] = True
for i in range(1, n + 1):
for j in range(target_sum + 1):
dp[i][j] = dp[i - 1][j]
if j >= nums[i - 1]:
dp[i][j] = dp[i][j] or dp[i - 1][j - nums[i - 1]]
min_diff = float('inf')
for j in range(target_sum, -1, -1):
if dp[n][j]:
min_diff = total_sum - 2 * j
break
return min_diff
nums = [1, 6, 11, 5]
min_sum = minSum(nums)
print("The minimum sum of subarrays with equal sum is:", min_sum)
```
方法二:单调栈
```python
def minSum(nums):
n = len(nums)
stack = []
res = 0
mod = 10**9 + 7
for i in range(n):
while stack and nums[i] < nums[stack[-1]]:
j = stack.pop()
k = stack[-1] if stack else -1
res += nums[j] * (i - j) * (j - k)
res %= mod
stack.append(i)
while stack:
j = stack.pop()
k = stack[-1] if stack else -1
res += nums[j] * (n - j) * (j - k)
res %= mod
return res
nums = [1, 6, 11, 5]
min_sum = minSum(nums)
print("The minimum sum of subarrays with equal sum is:", min_sum)
```
阅读全文