Google Interview: Find all contiguous subsequence in a given array of integers, whose sum falls in the given range. Can we do better than O(n^2)?

前端 未结 7 483
误落风尘
误落风尘 2021-01-30 02:35

Given an array of Integers, and a range (low, high), find all contiguous subsequence in the array which have sum in the range.

Is there a solution b

相关标签:
7条回答
  • 2021-01-30 03:29
    yes in my opinion it can be in O(n)
    
    struct subsequence
    {
    int first,last,sum;
    }s;
    
    function(array,low,high)
    {
    int till_max=0;
    s.first=0;s.last=0;s.sum=0;
    for(i=low;i<high;i++)
    {
    
    if(till_max+array[i]>array[i])
    {
    s.first=s.first;
    s.last=i;
    till_max+=array[i];
    }
    else
    {
    s.first=i;
    s.last=i;
    till_max=array[i];
    }
    if(till_max in range)
    {
    s.sum=till_max;
       printf("print values between first=%d and last=%d and sum=%d",s.first,s.last,s.sum);
    }
    }
    }
    
    0 讨论(0)
提交回复
热议问题