V
V
Valera Mayshev2019-04-21 01:05:31
C++ / C#
Valera Mayshev, 2019-04-21 01:05:31

How to determine the maximum sum of elements among arrays?

Greetings! Help please! I don’t understand how to determine the maximum sum among arrays in C ++. Since I don’t understand the term "maximum sum" itself ...
The task itself sounds like this: "Enter a one-dimensional array a1, a2, an. Calculate all the sums of three in a row going elements and among them determine the maximum amount. "
At the moment there is such a code:

#include <stdio.h>
#include <iostream>
#include <string>
#include <math.h>
using namespace std;
int main(){
  int arr_a1[3] = {3,4,5};
  int arr_a2[3] = {7,8,9};
  int arr_an[3] = {12,13,14};
  setlocale(LC_ALL, "Rus");
  cout <<"Массив a1 "" " << arr_a1[0] + arr_a1[1] + arr_a1[2]<< "\n" <<"Массив a2 "" " << arr_a2[0] + arr_a2[1] + arr_a2[2] << "\n" << "Массив an "" " << arr_an[0] + arr_an[1] + arr_an[2]<< endl;
}

Answer the question

In order to leave comments, you need to log in

3 answer(s)
V
Valera Maishev, 2019-04-26
@valeramayshev

Thanks to Roman for providing the code!
The code:

#include <iostream>
 
int sum(int* ptr, int count)
{
    int result = 0;
    for(int i = 0; i < count; ++i)
    {
        result += ptr[i];
    }
    return result;
}
 
int main()
{
  const int N  = 10;
  const int frame = 3;
 
  int a[N] = {0};
  int max = 0;
  int summ = 0;
 
  std::cout << "Enter values:\n";
  for(int i = 0; i < N; ++i)
  {
  	std::cout << "a[" << i << "] = "; 
  	std::cin >> a[i];
  	std::cout << "\n";
  }
 
  for(int i = 0; i < N - (frame - 1); ++i)
  {
      summ = sum(a + i, frame);
      if(summ > max)
      {
          max = summ;
      }
  }
  std::cout << max;
}

R
Ronald McDonald, 2019-04-21
@Zoominger

I think you misunderstood the task. This:
Means "one-dimensional array named a and indefinite size" (if N is not specified).
That is, there is only one array. You first enter its size (if, again, it is not specified immediately), then enter the numbers.
In it, look for what you need.

S
Stalker_RED, 2019-04-21
@Stalker_RED

Iterate over the array by adding each of the elements with two adjacent ones.
If the sum is greater than calculated in the previous step, remember it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question