Maximum subarrey

I've got a code that count maximum subarrey, but it only works when i know how many numbers will be in input. Could you help me with making it work when I don't know how many numvers will be in input?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
using namespace std;
int main () {
int l,g;
int t[7];
for (int x=0;x<=7;x++)
    cin >>t[x];
l = 0;
g = 0;
        for (int i=0;i<=8;i++) {
            if (t[i] > 0) {
                for (int j=i;j<=8;j++) {
                    l = l + t[j];
                    if (l > g) {
                        g = l;
                    }
                }
                l = 0;
            }
        }
    cout <<g;
}

closed account (E0p9LyTq)
If you do not know the number of elements a container will hold at compile time don't use an array. Use one of the STL container classes, such as a vector, deque or list. The STL containers other than <std::array> will grow as more elements are added to them.

http://www.cplusplus.com/reference/vector/vector/
http://www.cplusplus.com/reference/deque/
http://www.cplusplus.com/reference/list/

Lines 7, 11, 13: You're going to be making out of bounds references because your for loops are faulty. x,i,j should be <7. Your array is defined with a dimension of 7. This means the elements are are 0-6. [7] and [8] are out of bounds references.

The easiest way to handle a variable number of values, is to use a std::vector.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
using namespace std;
int main () 
{   int l,g, num, val;
    vector<int>     t;
    
    cout << "How many entries: ";
    cin >> num;
    for (int x=0; x<num; x++)
    {   cin >> val;
        t.push_back (val);
    }
    l = 0;
    g = 0;
    for (int i=0; i<num; i++) 
    {   if (t[i] > 0) 
        {   for (int j=i;j<num;j++) 
            {   l = l + t[j];
                if (l > g) 
                {   g = l;
                }
            }
            l = 0;
        }
    }
    cout << g;
}


Last edited on
Topic archived. No new replies allowed.