【问题标题】:Max Sum Path In Two Sorted Arrays in CC中两个排序数组中的最大和路径
【发布时间】:2020-12-18 17:13:39
【问题描述】:

我正在做 geeksforgeeks 的练习题。而且我无法解决问题并获得所需的输出。

https://practice.geeksforgeeks.org/problems/max-sum-path-in-two-arrays/1/?category[]=Arrays&company[]=Amazon&difficulty[]=0&page=1&sortBy=submissions&query=category[]Arrayscompany[]Amazondifficulty[]0page1sortBysubmissions

//I am finding the max path using the merge sort algo, where T(n)=O(m+n)
int MaxPath(int a[],int b[],int n,int m){
int i, j, result=0, sum1=0, sum2=0; // sum1 and sum2 store the sums of 1st and 2nd arrays respectively
while(i<n && j<m){
    if(a[i]<b[j]){
        sum1+=a[i++];
    }
    else if(a[i]>b[j]){
        sum2+=b[j++];
    }
    else{
        result+=Max(sum1,sum2);
        sum1=0;
        sum2=0;
        int temp=i;
        while(i<n && a[i]==b[j]){
            sum1+=a[i++];
        }
        while(j<m && a[temp]==b[j]){
            sum2+=b[j++];
        }
        result+=Max(sum1,sum2);
        sum1=0;
        sum2=0;
    }
}
while(i<n){
    sum1+=a[i++];
}
while(j<m){
    sum2+=b[j++];
}
result+=Max(sum1,sum2);
return result;
}

【问题讨论】:

  • Max() 是如何定义的?
  • @ryyker 我在我的程序中为此编写了一个函数。
  • 好的 - 在这种情况下,如果未初始化的变量是唯一的问题,那么这不是问题。但如果存在更多问题,最好提供minimal reproducible example,其中包括Max() 的定义,以帮助解决问题的人。 :)
  • 好的,谢谢@ryyker 我下次发布代码时一定会记住这一点。

标签: arrays c data-structures mergesort


【解决方案1】:

代码开头的未定义行为。本声明:

while(i<n && j<m){

在设置ij 的值之前调用:

int i, j, result=0, sum1=0, sum2=0;  

请注意,创建的其他项目已设置,但未设置 ij

因此,从这一点来看,这个 while 循环将如何执行还没有定义。在使用之前初始化所有变量。

【讨论】:

    猜你喜欢
    • 2015-12-05
    • 1970-01-01
    • 2017-08-08
    • 1970-01-01
    • 1970-01-01
    • 2012-06-28
    • 2017-08-01
    • 1970-01-01
    • 2021-11-29
    相关资源
    最近更新 更多