给定int
长度为n
的数组,将数组拆分为3部分并确保2个较小部分尽可能大。将int数组拆分为3部分,最大化2个较小部分的大小
拆分规则:
- 挑两个指数
a
和给定阵列的b
(0 < =一个< = B < = N-1) - 第一部分的尺寸是:所有阵列的总和从索引0到a-1(含)的条目
- 第二部分的大小是:索引a到b(含)的所有数组条目的总和
- 第三部分的大小是:来自b + 1到n-1(包含IVE)
- 空零件是可能..
预期的输出是2个小的部分(它们的大小)的总和。例如,n = 6
的数组和一些值被给出。 解决方案计算a = 2
,b = 3
,将阵列拆分为3部分:左侧部分大小为6 + 7 = 13
,中间部分为8 + 9 = 17
,右侧部分为4 + 5 = 9
。输出是13 + 9 = 22
(两个较小部分的总和)。
图形表示:
更多的例子:
[6,8,3,5,7,2,4,6]应被分成:
- Left(
6 + 8 = 14
) - Middle(
3 + 5 + 7 = 15
) - 右(
2 + 4 + 6 = 12
)
的输出被14 + 12 = 26
(2个小的部分的总和)
[9,12,4,7,10,2,5,8,11,3]应分成:
- 左(
9 + 12 + 4 = 25
) - 中东(
7 + 10 + 2 + 5 = 24
) - 右(
8 + 11 + 3 = 22
)
输出是22 + 24 = 46
(2个较小的部分的总和)
我的做法没有为给定的测试情况下工作:
// L is size of left part, M is size of middle part, R is size of right part
/* I start with all array entries in the middle part, then I put elements
out of the middle part into the left and right part (depending on which
is smaller) until one of them is larger than M, this approach works for
many cases, two exceptions are the first 2 arrays given as examples in
this post.
*/
long a = 1;
long b = n;
long L = R = 0;
long M = arr.sumOfAllArrayEntries;
long temp;
long[] arr = {9, 12, 4, 7, 10, 2, 5, 8, 11, 3};
while (M > Math.max(L, R)) {
if (L < R) {
// move leftmost element of M to L
temp = arr[(int) a++];
M -= temp;
L += temp;
}
else {
// move rightmost element of M to R
temp = arr[(int) b--];
M -= temp;
R += temp;
}
}
// finds maximum of M, L, R
temp = Math.max(M, Math.max(L, R));
// finds 2 smallest numbers out of M, L, R
if (temp == M)
temp = L + R;
else if (temp == L)
temp = M + R;
else if (temp == R)
temp = M + L;
// temp is equal to the sum of the 2 smaller parts
System.out.println("Output: " + temp);
好方法!这是给你的赞扬! –
尝试[4,3,2,9,8],输出应为17(分割为4 + 3 + 2 = 9,9,8)。你的算法返回15.另外oldbest变量似乎没有必要。有趣的做法! –
@AnnaVopureta漂亮的编辑 - 编辑 - 应该是一个while循环而不是if语句。 oldbest只是一个我忘记的调试变量。 – Dukeling