kadane的算法实现 input =(t = 1; n = 3; arr = { - 1,4,5})给出输出8但预期输出为9。
#include <iostream>
#include<cmath>
using namespace std;
int Max( int *arr, int n){
int currmax = arr[0];
int globalmax = arr[0];
for(int i = 1; i < n; i++) {
currmax= max(currmax, currmax + arr[i]);
if(currmax > globalmax)
globalmax = currmax;
}
return globalmax;
}
int main() {
int t;
cin >> t;
while(t--){
int n;
cin >> n;
int arr[n];
for(int i = 0; i < n; i++) cin >> arr[i];
cout << Max(arr, n) << " ";
}
}
答案 0 :(得分:0)
将currmax= max(currmax, currmax+arr[i])
更改为currmax= max(arr[i], currmax+arr[i])
,以便将当前值与数组值进行比较。
在你的情况下-1,4,5
currmax的价值将更新如下:
1. currmax = -1,currmax + arr [1] = 3(比较btw(4,3))
2. currmax = 4,currmax + arr [2] = 9(比较btw(5,9))
3. currmax = 9
代码如下:
#include <iostream>
#include <cmath>
using namespace std;
int Max( int *arr, int n){
int currmax=arr[0];
int globalmax=arr[0];
for(int i=1;i<n;i++) {
currmax= max(arr[i], currmax+arr[i]); // your code line was wrong here check and try
if(currmax>globalmax)
globalmax=currmax;
}
return globalmax;
}
int main() {
int t;
cin>>t;
while(t--){
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++) cin>>arr[i];
cout<<Max(arr,n)<<" ";
}
}