c++ - 查找具有给定总和的子数组

标签 c++ arrays algorithm

问题陈述是:

Given an unsorted array of nonnegative integers, find a continous subarray which adds to a given number.

Examples:

Input: arr[] = {1, 4, 20, 3, 10, 5}, sum = 33
Ouptut: Sum found between indexes 2 and 4

Input: arr[] = {1, 4, 0, 0, 3, 10, 5}, sum = 7
Ouptut: Sum found between indexes 1 and 4

Input: arr[] = {1, 4}, sum = 0
Output: No subarray found

基于对来自 this post 的解决方案的解释以下解决方案不适用于负数:

/* An efficient program to print subarray with sum as given sum */
#include<stdio.h>

/* Returns true if the there is a subarray of arr[] with sum equal to 'sum'
   otherwise returns false.  Also, prints the result */
int subArraySum(int arr[], int n, int sum)
{
    /* Initialize curr_sum as value of first element
       and starting point as 0 */
    int curr_sum = arr[0], start = 0, i;

    /* Add elements one by one to curr_sum and if the curr_sum exceeds the
       sum, then remove starting element */
    for (i = 1; i <= n; i++)
    {
        // If curr_sum exceeds the sum, then remove the starting elements
        while (curr_sum > sum && start < i-1)
        {
            curr_sum = curr_sum - arr[start];
            start++;
        }

        // If curr_sum becomes equal to sum, then return true
        if (curr_sum == sum)
        {
            printf ("Sum found between indexes %d and %d", start, i-1);
            return 1;
        }

        // Add this element to curr_sum
        if (i < n)
          curr_sum = curr_sum + arr[i];
    }

    // If we reach here, then no subarray
    printf("No subarray found");
    return 0;
}

我尝试考虑了几种不同的输入场景,但我想不出输入数组包含负数而不会产生正确输出的情况。这是一个有效的负数输入数组:

int arr[] = { 15, 14, -2, 3, -5, 14};

当帖子说该解决方案不适用于负数时,指的是哪些输入案例?

最佳答案

这个解决方案依赖于这样一个事实,即当我们删除一个元素时,我们的总和会减少,但负数与这个假设相矛盾。

最短的例子是这样的情况 -1 5 2 当我们寻找和为5的子数组时,操作如下:

add -1, sum = -1
add 5, sum = 4
add 2, sum = 6
remove -1, sum = 7
remove 5, sum = 2

我们已经到了列表的末尾,但还没有找到所需的子数组。

关于c++ - 查找具有给定总和的子数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39320735/

相关文章:

c++ - Windows MFC 对话框在无效时闪烁

algorithm - 在停留在 "road"的假设下寻找连接两点的最短路径?

arrays - 用数组填充下拉列表

r - 查找 DAG 中节点值的累积和

algorithm - 在访问所有单元格的 3D 体素空间中的两点之间走一条线

c++ - boost程序选项的parse_config_file如何解析multitoken

c++ - 当我从文件目录中读取值时,试图将用户定义的对象插入到 vector 中

c++ - OpenGL:地形未绘制(高度图)

python - 将 numpy 数组作为单列保存到 txt 文件?

arrays - 如何在结构(或等效结构)中定义指向可变长度数组 (VLA) 的指针?