From 8fada6524f4512951b036c12675ecf50018c267a Mon Sep 17 00:00:00 2001 From: ApurvaR1 Date: Thu, 30 Nov 2023 18:31:15 -0500 Subject: [PATCH] r program to find maximum sum --- ...nd_the_maximum_sum_of_a_contiguous_subarray.r | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 program/program/find-the-maximum-sum-of-a-contiguous-subarray/find_the_maximum_sum_of_a_contiguous_subarray.r diff --git a/program/program/find-the-maximum-sum-of-a-contiguous-subarray/find_the_maximum_sum_of_a_contiguous_subarray.r b/program/program/find-the-maximum-sum-of-a-contiguous-subarray/find_the_maximum_sum_of_a_contiguous_subarray.r new file mode 100644 index 000000000..bce5d2e79 --- /dev/null +++ b/program/program/find-the-maximum-sum-of-a-contiguous-subarray/find_the_maximum_sum_of_a_contiguous_subarray.r @@ -0,0 +1,16 @@ +findMaxSubarraySum <- function(arr) { + max_so_far <- arr[1] + max_ending_here <- arr[1] + + for (i in 2:length(arr)) { + max_ending_here <- max(arr[i], max_ending_here + arr[i]) + max_so_far <- max(max_so_far, max_ending_here) + } + + return(max_so_far) +} + +# Test the function with the provided input +input_array <- c(-2, -3, 4, -1, -2, 1, 5, -3) +max_sum <- findMaxSubarraySum(input_array) +print(max_sum)