Kadane algorithm is used to find:a)Maximum sum subsequence in an array...
Kadane's algorithm is used to find the maximum sum subarray in an array.
Kadane's algorithm is a popular algorithm used to solve the maximum subarray problem. It efficiently finds the contiguous subarray with the largest sum in an array of numbers, also known as the maximum sum subarray.
Understanding the problem:
Given an array of numbers, the task is to find a subarray (contiguous sequence of elements) with the maximum sum. For example, in the array [-2, 1, -3, 4, -1, 2, 1, -5, 4], the maximum sum subarray is [4, -1, 2, 1], which has a sum of 6.
Algorithm:
Kadane's algorithm follows a simple and efficient approach to solve this problem. It iterates through the array and keeps track of the maximum sum encountered so far. It also keeps track of the current sum of the subarray being considered. The algorithm updates these values as it traverses the array.
Here are the steps of the algorithm:
1. Initialize two variables: max_so_far and max_ending_here, both set to the first element of the array.
2. Iterate through the array from the second element onwards.
3. For each element, update max_ending_here as the maximum of the current element and the current element plus max_ending_here.
4. Update max_so_far as the maximum of max_so_far and max_ending_here.
5. Repeat steps 3-4 for all elements in the array.
6. After the iteration, max_so_far will hold the maximum sum of a subarray in the given array.
Example:
Let's apply Kadane's algorithm to the array [-2, 1, -3, 4, -1, 2, 1, -5, 4]:
- Start: max_so_far = -2, max_ending_here = -2
- Iteration 1: max_ending_here = max(1, 1 + -2) = 1, max_so_far = max(-2, 1) = 1
- Iteration 2: max_ending_here = max(-3, -3 + 1) = -2, max_so_far = max(1, -2) = 1
- Iteration 3: max_ending_here = max(4, 4 + -2) = 4, max_so_far = max(1, 4) = 4
- Iteration 4: max_ending_here = max(-1, -1 + 4) = 3, max_so_far = max(4, 3) = 4
- Iteration 5: max_ending_here = max(2, 2 + 3) = 5, max_so_far = max(4, 5) = 5
- Iteration 6: max_ending_here = max(1, 1 + 5) = 6, max_so_far = max(5, 6) = 6
- Iteration 7: max_ending_here = max(-5, -5 + 6) = 1, max_so_far = max(6, 1) = 6
- Iteration 8