Given an array arr[] of size N. The task is to find the sum of the contiguous subarray within a arr[] with the largest sum.

0

 Given an array arr[] of size N. The task is to find the sum of the contiguous subarray within a arr[] with the largest sum.

Cpp Program Code:


In this code, we initialize max_sum and curr_sum to the first element of the array. We then iterate through the rest of the array and update curr_sum as the maximum of the current element and the sum of the current element and the previous curr_sum. We also update max_sum as the maximum of max_sum and curr_sum at each iteration. Finally, we return max_sum as the result. This algorithm has a time complexity of O(n), where n is the length of the input array.

Python Program code:


In this code, we initialize max_sum and curr_sum to the first element of the array. We then iterate through the rest of the array and update curr_sum as the maximum of the current element and the sum of the current element and the previous curr_sum. We also update max_sum as the maximum of max_sum and curr_sum at each iteration. Finally, we return max_sum as the result. This algorithm has a time complexity of O(n), where n is the length of the input array.



Post a Comment

0Comments
Post a Comment (0)