Given an integer array of N elements, find the maximum sum of continuous elements in the array.
Sample Inputs/Outputs
Sample Input(s) | Sample Output(s) |
---|---|
The first line of the input represents the number of test cases, and each subsequent line represents one test case. Each test case consists of a line of numbers separated by spaces: The first integer represents the length of the array, N, which ranges from 1 to 100. The next N integers are integers ranging from -10000 to 10000. | For each test data set, output the maximum sum of consecutive elements in one line. |
3 5 1 2 -3 4 5 5 1 2 3 4 5 6 10 -5 7 6 -1 -3 | 9 15 18 |
Thought Process
Use a for loop to store the data in an array/vector. Then, use another for loop to set the current starting point for summation. Inside this loop, run another for loop from the value obtained in the outer loop to the end of the array/vector. In each iteration, add the numbers in the sequence to a variable and perform a comparison to update the maximum value. Finally, output the variable containing the maximum value.
Sample Code-ZeroJudge D784: Sum of Continuous Elements
#include <iostream>
#include <vector>
using namespace std;
int main() {
cin.sync_with_stdio(0);
cin.tie(0);
int N;
cin >> N;
for (int i = 0; i<N; i++)
{
int M;
cin >> M;
vector<int>num;
for (int j = 0; j<M; j++)
{
int tmp;
cin >> tmp;
num.push_back(tmp);
}
int max = -999;
for (int j = 0; j<M; j++)
{
int sum = 0;
for (int k = j; k<M; k++)
{
sum += num[k];
if (sum > max) max = sum;
}
}
cout << max << endl;
}
}
//ZeroJudge D784
//Dr. SeanXD