1

Find out the maximum sub-array of non negative numbers from an array. The sub-array should be continuous. That is, a sub-array created by choosing the second and fourth element and skipping the third element is invalid.

Maximum sub-array is defined in terms of the sum of the elements in the sub-array. Sub-array A is greater than sub-array B if sum(A) > sum(B).

This is my solution:

vector<int> Solution::maxset(vector<int> &A) {
// Do not write main() function.
// Do not read input, instead use the arguments to the function.
// Do not print the output, instead return values as specified
// Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details

    vector <int> bla;
    int sum[100]={0};
    int k = 0;
    int j = 1;

    for (int i =0; i < A.size(); i++){
        if (A[i] > -1){
            sum[k] = A[i] + sum[k];
        }
        else {
            k++;
        }
    } 

    cout<<sum[0]<<" ";
    cout<<sum[1]<<" ";
    cout << sum[2] << " ";

    int s = 0;

    for (int i =0; i< 100; i++){
        if (s < sum[i]){
            s = sum[i];
            k = i;
        }
    }

    cout << s;

    int count = 0;
    for (int i =0; i < A.size(); i++){
        if (A[i] < 0) {
            count ++;
        }

        if (count == k) {
            int j = i+1;
            int x = 0;
            while (A[j] > 0 && j< (A.size()-1)) {
                //  bla[x] = A[j];
                x++;
                j++;
            }
        }
    } 

    return bla;
}

If I uncomment the line bla[x] = A[j], I get segmentation error. Can someone explain how to undetstand this error? I read it somewhere that there is not enough space in stack. I do not understand how. Thank you

Akriti Anand
  • 166
  • 3
  • 17
  • 2
    Now is the right time to learn how to use a debugger. BTW, your code is flawed. – WhiZTiM Sep 02 '17 at 12:04
  • 2
    When you define a vector without a specific size, it will be *empty*. Any indexing in it will be *out of bounds*. – Some programmer dude Sep 02 '17 at 12:04
  • @Someprogrammerdude then how do I assign values to a vector if I can't index it? – Akriti Anand Sep 02 '17 at 12:06
  • 1
    [Any good beginners book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) or tutorial would tell you about the [`push_back`](http://en.cppreference.com/w/cpp/container/vector/push_back) function. – Some programmer dude Sep 02 '17 at 12:07
  • Since you want to add to the end of vector (you are starting with x=0 and go up) use push_back - vector will grow as you add values – Artemy Vysotsky Sep 02 '17 at 12:07
  • Oh yes, that also throws the same error – Akriti Anand Sep 02 '17 at 12:07
  • what are you going to do ? – Mohsen_Fatemi Sep 02 '17 at 12:07
  • If you are getting same error check out `vector &A`, because you have two vectors that should have been validated. Just use hints from SPD. – Guillotine Sep 02 '17 at 12:12
  • 1
    If `bla.push_back(A[j])` is giving you a crash, you have some other much more serious problem. I suggest reading [How to debug small programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) by Eric Lippert, and learn how to use a debugger to step through your program line by line to find out what the problem might be. Also tools such as [Valgrind](http://valgrind.org/) will also help you find out problems. – Some programmer dude Sep 02 '17 at 12:14
  • And you *do* have a much bigger problem: `A[j] > 0 || j< (A.size()-1)` ***will*** go out of bounds. Change the order and the condition. This is something that you should have found out about by using debuggers or Valgrind. – Some programmer dude Sep 02 '17 at 12:16
  • @Someprogrammerdude thank you for suggestion. I will try them out. – Akriti Anand Sep 02 '17 at 12:18
  • 1
    in the very first loop you allow variable `k` grow without limit. There is no guarantee that it is less than 100. Probably you corrupt memory there. – Serge Sep 02 '17 at 12:50
  • `bla` is a `std::vector` with no elements. The `operator[]()` for a `std::vector` gives undefined behaviour if used to access a non-existent element. It does not magically resize to make the access work - if you want the array resized, you need to write code to resize BEFORE using indexing with `operator[]()`. Also, the offending loop does not check the value of `x` before accessing `bla[x]` so - even if `bla` did contain elements - the loop may still attempt to access non-existent elements of `bla`. Read the documentation of vector to work out how to fix. – Peter Sep 02 '17 at 14:03

1 Answers1

0

You can pass the size to a vector object or you can call it's default constructor which creates a vector object with 0 size.

std::vector<int> vecInt(10);
for(int i(0); i < vecInt.size(); i++)
    vecInt[i] = i;

Or you can declare a vector with size 0:

std::vector<int> vecInt;
vecInt[0] = 10; // segfault

Because you try to store values in an un-allocated space.

To solve such problem use push_back to store and pop to clear:

So your example can be like this:

while (A[j] > 0 || j< (A.size()-1)) {
     //  bla[x] = A[j];
     bla.push_back(A[j]);
     x++;
     j++;
}
Raindrop7
  • 3,889
  • 3
  • 16
  • 27
  • 1
    Note: contrary to the comment in-code, the second of these will *not* seg-fault because the loop body will never be entered. `vecInt.size()` will be zero, and as such, `i < vecInt.size()`, where `i` is zero, will be *false* from the outset, and the for-loop will break immediately. In short, other than declaring an empty vector, the second code will do nothing, but will *not* seg-fault. – WhozCraig Sep 02 '17 at 13:44
  • @WhozCraig: Yes thank you! you are right. I didn't really notice that. – Raindrop7 Sep 02 '17 at 13:51