+ 1
Why my " Kadane's Algorithm " is not giving the right answer ??
#include <iostream> using namespace std; int main() { system("cls"); const int n = 8; // or use #define n 8 int arr[] = {1, 12, -3, 4, 5, 7, -4, -8}; int curr_sum = 0; int max_sum = INT32_MIN; for (int i = 0; i < n; i++) { curr_sum += arr[i]; if (arr[i] < 0) { curr_sum = 0; } max_sum = max(curr_sum, max_sum); } cout << max_sum; return 0; }
4 ответов
+ 3
int curr_sum = INT32_MIN, max_sum = 0;
for (int i = 0; i < n; i++) {
max_sum += arr[i];
if (curr_sum < max_sum)
curr_sum = max_sum;
if (max_sum < 0)
max_sum = 0;
}
cout << curr_sum;
+ 1
Harshit Gupta describe your problem in more detail.
What result do you expect to get?
0
Harshit Gupta ,
That's C++, right? Please remove the C tag.
0
From what I saw from this article, it seems the problems lies in the if statement.
https://www.geeksforgeeks.org/largest-sum-contiguous-subarray/