假设我们有一个数组A,它有n个元素。我们的任务是将数组A分为两个子数组,以使每个子数组的总和相同。假设数组A = [2、3、4、1、4、5],输出为1,因此采用1之前和1之后的子数组。[2,3,4]和[4,5]。
为了解决这个问题,我们将计算除right_sum中的第一个元素以外的整个数组。考虑到这是分区元素。我们将从左到右遍历。从right_sum中减去一个元素并将一个元素添加到left_sum中,我们得出right_sum = left_sum的意义。
#include<iostream>
using namespace std;
int getPartitionElement(int arr[], int size) {
int right = 0, left = 0;
for (int i = 1; i < size; i++)
right += arr[i];
for (int i = 0, j = 1; j < size; i++, j++) {
right -= arr[j];
left += arr[i];
if (left == right)
return arr[i + 1];
}
return -1;
}
int main() {
int arr[] = { 2, 3, 4, 1, 4, 5 };
int size = sizeof(arr) / sizeof(arr[0]);
cout << "Partition element: " << getPartitionElement(arr, size);
}输出结果
Partition element: 1