gpt4 book ai didi

algorithm - 产生给定总和和乘积的子数组

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:05:48 26 4
gpt4 key购买 nike

给定一个长度为 N 的数组,你将如何找到最小长度其和为 S 且其积为 P 的连续子数组。例如 5 6 1 4 6 2 9 7 for S = 17, Ans = [6, 2, 9] for P = 24, Ans = [4 6]

最佳答案

就从左到右,对所有数字求和,如果总和 > S,则丢弃左边的数。

import java.util.Arrays;

public class test {
public static void main (String[] args) {
int[] array = {5, 6, 1, 4, 6, 2, 9, 7};
int length = array.length;
int S = 17;
int sum = 0; // current sum of sub array, assume all positive
int start = 0; // current start of sub array
int minLength = array.length + 1; // length of minimum sub array found
int minStart = 0; // start of of minimum sub array found
for (int index = 0; index < length; index++) {
sum = sum + array[index];
// Find by add to right
if (sum == S && index - start + 1 < minLength) {
minLength = index - start + 1;
minStart = start;
}
while (sum >= S) {
sum = sum - array[start];
start++;
// Find by minus from left
if (sum == S && index - start + 1 < minLength) {
minLength = index - start + 1;
minStart = start;
}
}
}
// Found
if (minLength != length + 1) {
System.out.println(Arrays.toString(Arrays.copyOfRange(array, minStart, minStart + minLength)));
}
}
}

对于你的例子,我认为是OR

Productsum 没有什么不同,除了计算。

关于algorithm - 产生给定总和和乘积的子数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5535040/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com