Skip to content

Commit e028523

Browse files
authored
Merge pull request #363 from Yashgabani845/yash-work4
kadane's Algorithm Solution added
2 parents 355b255 + d0569fd commit e028523

File tree

1 file changed

+270
-0
lines changed

1 file changed

+270
-0
lines changed
Lines changed: 270 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,270 @@
1+
---
2+
id: kadane's-algorithm
3+
title: Kadane's Alogrithm (Geeks for Geeks)
4+
sidebar_label: 0003 - Kadane's Algorithm
5+
tags:
6+
- intermediate
7+
- Array
8+
- Dynamic Programming
9+
- Data Structure
10+
- Algorithms
11+
12+
description: "This is a solution to the Kadane's Algorithm problem on Geeks for Geeks."
13+
---
14+
15+
This tutorial contains a complete walk-through of the Kadane's Algorithm problem from the Geeks for Geeks website. It features the implementation of the solution code in three programming languages: Python ,C++ ,java.
16+
17+
## Problem Description
18+
19+
Given an array Arr[] of N integers, find the contiguous sub-array (containing at least one number) which has the maximum sum and return its sum.
20+
21+
## Examples
22+
23+
**Example 1:**
24+
25+
```
26+
Input:
27+
N = 5
28+
Arr[] = {1,2,3,-2,5}
29+
Output:
30+
9
31+
Explanation:
32+
Max subarray sum is 9
33+
of elements (1, 2, 3, -2, 5) which
34+
is a contiguous subarray.
35+
```
36+
37+
**Example 2:**
38+
39+
```
40+
Input:
41+
N = 4
42+
Arr[] = {-1,-2,-3,-4}
43+
Output:
44+
-1
45+
Explanation:
46+
Max subarray sum is -1
47+
of element (-1)
48+
```
49+
50+
## Your Task
51+
52+
You don't need to read input or print anything. Your task is to complete the function `maxSubarraySum()` which takes Arr[] and N as input parameters and returns the sum of subarray with maximum sum.
53+
54+
Expected Time Complexity: $O(N)$
55+
Expected Auxiliary Space: $O(1)$
56+
57+
## Constraints
58+
59+
1. $(1 \leq N \leq 10^6)$
60+
2. $(-10^7 \leq A[i] \leq 10^7)$
61+
62+
## Solution Approach
63+
64+
### Brute Force Approach
65+
66+
#### Intuition:
67+
Try all possible subarrays by using nested loops and pick the subarray which has the maximum sum.
68+
69+
#### Implementation:
70+
1. Keep an answer variable to store the maximum subarray sum.
71+
2. Run a loop(i).
72+
3. Run a nested loop from i till the end of the array.
73+
4. Generate all subarrays starting from the ith index and compare its sum with the answer and update the answer with the maximum one.
74+
5. Return the answer.
75+
76+
#### Code (C++):
77+
78+
```cpp
79+
class Solution{
80+
public:
81+
// arr: input array
82+
// n: size of array
83+
//Function to find the sum of contiguous subarray with maximum sum.
84+
long long maxSubarraySum(int arr[], int n){
85+
86+
// Your code here
87+
long long ans=arr[0];
88+
for(int i=0;i<n;i++) {
89+
long long temp=0;
90+
for(int j=i;j<n;j++) {
91+
temp += arr[j];
92+
ans = max(ans,temp);
93+
}
94+
}
95+
return ans;
96+
}
97+
};
98+
```
99+
100+
#### Complexity:
101+
- Time Complexity: $(O(N^2))$, As we are running a nested loop over the length of the array.
102+
- Space Complexity: $(O(1))$, Here no extra space is used.
103+
104+
### Kadane's Algorithm
105+
106+
#### Intuition:
107+
Kadane’s algorithm works on the principle of continuously adding the array value to the current sum so far and updating the max sum every time. Whenever the current sum becomes negative, initialize it to zero and continue the process. By this approach, only one loop is required to compute the maximum sum contiguous subarray, reducing the time complexity to linear $(O(N))$.
108+
109+
#### Implementation:
110+
1. Initialize the variables `max_so_far = arr[0]` (stores the maximum sum of contiguous subarray found so far) and `max_ending_here = 0` (stores the maximum sum contiguous subarray ending at the current index).
111+
2. Run a for loop from 0 to N-1 and for each index i:
112+
- Add the arr[i] to `max_ending_here`.
113+
- If `max_so_far` is less than `max_ending_here`, then update `max_so_far` to `max_ending_here`.
114+
- If `max_ending_here` < 0, then update `max_ending_here = 0`.
115+
3. Return `max_so_far`.
116+
117+
#### Example:
118+
Let's take the example: {-2, -3, 4, -1, -2, 1, 5, -3}
119+
- `max_so_far = arr[0] = -2`
120+
- `max_ending_here = 0`
121+
122+
For i=0, a[0] = -2:
123+
- `max_ending_here = max_ending_here + (-2)`
124+
- Set `max_ending_here = 0` because `max_ending_here < 0`
125+
- Set `max_so_far = -2`
126+
127+
For i=1, a[1] = -3:
128+
- `max_ending_here = max_ending_here + (-3)`
129+
- Since `max_ending_here = -3` and `max_so_far = -2`, `max_so_far` will remain -2
130+
- Set `max_ending_here = 0` because `max_ending_here < 0`
131+
132+
For i=2, a[2] = 4:
133+
- `max_ending_here = max_ending_here + (4)`
134+
- `max_ending_here = 4`
135+
- `max_so_far` is updated to 4 because `max_ending_here` greater than `max_so_far` which was -2 till now
136+
137+
For i=3, a[3] = -1:
138+
- `max_ending_here = max_ending_here + (-1)`
139+
- `max_ending_here = 3`
140+
141+
For i=4, a[4] = -2:
142+
- `max_ending_here = max_ending_here + (-2)`
143+
- `max_ending_here = 1`
144+
145+
For i=5, a[5] = 1:
146+
- `max_ending_here = max_ending_here + (1)`
147+
- `max_ending_here = 2`
148+
149+
For i=6, a[6] = 5:
150+
- `max_ending_here = max_ending_here + (5)`
151+
- `max_ending_here = 7`
152+
- `max_so_far` is updated to 7 because `max_ending_here` is greater than `max_so_far`
153+
154+
For i=7, a[7] = -3:
155+
- `max_ending_here = max_ending_here + (-3)`
156+
- `max_ending_here = 4`
157+
158+
Hence, `max_so_far = 7`.
159+
160+
#### Code (C++):
161+
162+
```cpp
163+
class Solution{
164+
public:
165+
//Function to find the sum of contiguous subarray with maximum sum.
166+
long long maxSubarraySum(int a[], int n){
167+
168+
long long maxh = 0, maxf = a[0];
169+
170+
//Iterating over the array.
171+
for(int i=0;i<n;i++)
172+
{
173+
//Updating max sum till current index.
174+
maxh+=a[i];
175+
//Storing max sum so far by choosing maximum between max
176+
//sum so far and max till current index.
177+
if(maxf<maxh)
178+
maxf=maxh;
179+
180+
//If max sum at current index is negative, we do not need to add
181+
//it to result so we update it to zero.
182+
if(maxh<0)
183+
maxh=0;
184+
185+
}
186+
//returning the result.
187+
return maxf;
188+
189+
}
190+
};
191+
```
192+
193+
#### Code (Java):
194+
195+
```java
196+
class Solution {
197+
//Function to find the sum of contiguous subarray with maximum sum.
198+
long maxSubarraySum(int arr[], int n){
199+
200+
long maxh = 0, maxf = arr[0];
201+
202+
//Iterating over the array.
203+
for(int i = 0; i < n; i++){
204+
205+
//Updating max sum till current index.
206+
maxh += arr[i];
207+
//Storing max sum so far by choosing maximum between max
208+
//sum so far and max sum till current index.
209+
if(maxf < maxh)
210+
maxf = maxh;
211+
212+
//If max sum till current index is negative, we do not need to add
213+
//it to result so we update it to zero.
214+
if(maxh < 0)
215+
maxh = 0;
216+
}
217+
//returning the result.
218+
return maxf;
219+
}
220+
}
221+
```
222+
223+
#### Code (Python):
224+
225+
```python
226+
class Solution:
227+
#Function to find the sum of contiguous subarray with maximum sum.
228+
def maxSubArraySum(self,a,size):
229+
230+
max_so_far = -9999999 - 1
231+
max_ending_here = 0
232+
233+
#Iterating over the array.
234+
for i in range(0, size):
235+
#Updating max sum till current index.
236+
max_ending_here = max_ending_here + a[i]
237+
238+
#Storing max sum so far by choosing maximum between max
239+
#sum so far and max sum till current index.
240+
if (max_so_far < max_ending_here):
241+
max_so_far = max_ending_here
242+
243+
#If max sum till current index is negative, we do not need to add
244+
#it to result so we update it to zero.
245+
if max_ending_here < 0:
246+
max_ending_here = 0
247+
248+
#returning the result.
249+
return max_so_far
250+
```
251+
252+
#### Complexity:
253+
- Time Complexity: $(O(N))$, where $O(N)$ is the size of the array as we are looping once over the whole array.
254+
- Space Complexity: $(O(1))$, Here we are not using extra space.
255+
256+
## Conclusion
257+
258+
The problem of finding the maximum sum of a contiguous subarray can be effectively solved using Kadane's Algorithm, which operates in linear time $(O(N))$. This algorithm is highly efficient and utilizes constant space, making it suitable for large input sizes as specified in the constraints. The brute force approach, while conceptually simpler, is computationally expensive with a time complexity of $(O(N^2))$ and is not suitable for larger arrays.
259+
260+
By iterating through the array and maintaining the current
261+
262+
subarray sum and the maximum subarray sum found so far, Kadane's Algorithm offers an optimal solution. This approach ensures that even in the worst case, where all elements are negative, the algorithm correctly identifies the largest element, which is the maximum sum subarray in such scenarios.
263+
264+
The provided implementations in C++, Java, and Python demonstrate how Kadane's Algorithm can be applied across different programming languages, ensuring versatility and ease of integration into various codebases.
265+
266+
## References
267+
268+
- **GeeksforGeeks Problem:** [Geeks for Geeks Problem](https://www.geeksforgeeks.org/problems/kadanes-algorithm-1587115620/1)
269+
- **Solution Link:** [Kadane's Algorithm on Geeks for Geeks](https://www.geeksforgeeks.org/problems/kadanes-algorithm-1587115620/1)
270+
- **Authors GeeksforGeeks Profile:** [Yash](https://www.geeksforgeeks.org/user/gabaniyxn26/)

0 commit comments

Comments
 (0)