From d60c102c98c1f862c7c23210273fa304a0b5fc01 Mon Sep 17 00:00:00 2001 From: okaydivyansh Date: Thu, 5 Oct 2023 16:15:46 +0530 Subject: [PATCH] added-ans1.4 --- Answer1.4.cpp | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 Answer1.4.cpp diff --git a/Answer1.4.cpp b/Answer1.4.cpp new file mode 100644 index 0000000..95d9ff8 --- /dev/null +++ b/Answer1.4.cpp @@ -0,0 +1,27 @@ +#include +#include + +int kadanesAlgorithm(const std::vector& 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 nums = {-2, 1, -3, 4, -1, 2, 1, -5, 4}; + int maxSubarraySum = kadanesAlgorithm(nums); + + std::cout << "Maximum subarray sum: " << maxSubarraySum << std::endl; + + return 0; +}