Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions Answer1.4.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
#include <iostream>
#include <vector>

int kadanesAlgorithm(const std::vector<int>& nums) {
int maxEndingHere = nums[0]; // Initialize maxEndingHere and maxSoFar to the first element of the array
int maxSoFar = nums[0];

for (int i = 1; i < nums.size(); ++i) {
// Calculate the maximum ending at the current element
maxEndingHere = std::max(nums[i], maxEndingHere + nums[i]);

// Update the maximum subarray sum seen so far
maxSoFar = std::max(maxSoFar, maxEndingHere);
}

return maxSoFar;
}

int main() {
// Example usage:
std::vector<int> nums = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
int maxSubarraySum = kadanesAlgorithm(nums);

std::cout << "Maximum subarray sum: " << maxSubarraySum << std::endl;

return 0;
}