+ 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; }

11th Feb 2024, 2:34 AM
Harshit Gupta
4 Antworten
+ 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;
11th Feb 2024, 9:05 AM
JaScript
JaScript - avatar
+ 1
Harshit Gupta describe your problem in more detail. What result do you expect to get?
11th Feb 2024, 7:32 AM
Solo
Solo - avatar
0
Harshit Gupta , That's C++, right? Please remove the C tag.
11th Feb 2024, 2:50 AM
Rain
Rain - avatar
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/
11th Feb 2024, 9:01 AM
Wong Hei Ming
Wong Hei Ming - avatar