使用给定的sum子数组查找子数组应该是连续的

时间:2014-10-16 11:03:39

标签: algorithm data-structures

查找具有给定sum子数组的子数组应该是连续的。
这个问题来自GeeksForGeeks。 enter link description here

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) // Check This
        {
            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;
}

在此我们使用条件 while(curr_sum&gt; sum&amp;&amp; start&lt; i-1)。我认为我们不需要将开始与i-1进行比较。我们只能在(curr_sum&gt; sum)时执行此。请回复。

1 个答案:

答案 0 :(得分:0)

你在某种程度上是正确的,但更接近检查问题定义:

  • 输入:arr [] = {1,4},sum = 0

  • 输出:未找到子阵列

通过提议的修改,算法的行为会有所不同。