简体   繁体   English

在数字字段中查找最大总和

[英]Finding the maximum sum in a field of numbers

I have to write a program that sums up sequential elements of an array and outputs the maximum sum. 我必须编写一个程序来汇总数组的顺序元素并输出最大总和。 As you will see my algorithm won't work if all elements are negative. 正如您将看到的,如果所有元素都是负数,我的算法将无效。

#include <iostream>

int main()
{
    int nums[1000] = {-1,-3,-4,-2,-5,-1,-9,-4,-2,-2};
    int sums[100][100];
    int n = 9;

    for(int i = 0; i <= n; i++) {
        for(int j = n; j >= i; j--) {
            for(int k = j; k >= i; k--) {
                sums[i][j] += nums[k];
            }
        }

    }

    int max_sum = 0; 
    int max_begin;
    int max_end;

     for(int i = 0; i <= n; i++) {
        for(int j = i+1; j <= n; j++){
                std::cout << "i = " << i << " j = " << j << ": " << sums[i][j] << "\n";
            if(max_sum < sums[i][j]) {
                max_sum = sums[i][j];
                max_begin = i;
                max_end = j;
                }
            }
        }

    std::cout << "Maximum: " << max_sum << " bei i = " << max_begin << " bis j = " << max_end;

    return 0;
}

I already tried this solution 我已经尝试过这个解决方案

#include <climits>
...
int max_sum = INT_MIN;
...

While this works perfectly fine we didn't have climits in our lecture yet so I'm looking for another way. 虽然这个工作非常好,但我们的讲座还没有攀登,所以我正在寻找另一种方式。

Change to: 改成:

int max_sum = sums[0][0];

This way you will never have to worry about the range of numbers. 这样您就不必担心数字的范围。

This is one of the main motivations for a std::optional type (when all values in a range are valid). 这是std :: optional类型的主要动机之一(当范围中的所有值都有效时)。 If you cannot use it, we can imitate it for our purposes with a simple boolean: 如果你不能使用它,我们可以用一个简单的布尔值来模仿它:

bool max_set = false;
int max_sum = 0;

// ...
if (!max_set || max_sum < sums[i][j]){
   max_set = true;
   max_sum = sums[i][j];
}

We can make a simple class to further imitate it if we'd like (untested code): 如果我们愿意(未经测试的代码),我们可以创建一个简单的类来进一步模仿它:

class optional_int{
   bool is_set = false;
   int value = 0;
public:
   bool operator()() const{return is_set;}
   int& operator=(int _value){value = _value; is_set=true; return value;}
   int& get(){
      if (!is_set){throw std::logic_error("attempting to access unset optional");}
      return value;
};

optional_int max_sum;
//...
if (!max_sum || max_sum.get() < sums[i][j]){
   max_sum = sums[i][j];
}

We can continue to make this type more and more generic, but we'd only be re-implementing std::optional 我们可以继续使这种类型越来越通用,但我们只是重新实现std::optional

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM