Embark on a journey of knowledge! Take the quiz and earn valuable credits.
Take A QuizChallenge yourself and boost your learning! Start the quiz now to earn credits.
Take A QuizUnlock your potential! Begin the quiz, answer questions, and accumulate credits along the way.
Take A Quiz
🧠 Problem Statement
Given:
An array of integers (can include negatives).
Task:
Find the contiguous subarray with the maximum sum, and return
that sum.
🧾 Sample Input/Output
Input:
int[] arr = {-2, 1, -3, 4, -1, 2, 1, -5, 4}
Output:
6
Explanation:
The subarray [4, -1, 2, 1] has the largest sum = 6
🔍 Brute Force Approach:
Check All Subarrays
public
static int maxSubarrayBrute(int[] arr) {
int max = Integer.MIN_VALUE;
for (int i = 0; i < arr.length; i++) {
int sum = 0;
for (int j = i; j < arr.length; j++)
{
sum += arr[j];
max = Math.max(max, sum);
}
}
return max;
}
⛔ Time: O(n²)
✅
Works, but not scalable
✅ Kadane’s Algorithm – Optimal
Solution
public
static int maxSubarrayKadane(int[] arr) {
int maxSoFar = arr[0];
int currentMax = arr[0];
for (int i = 1; i < arr.length; i++) {
currentMax = Math.max(arr[i],
currentMax + arr[i]);
maxSoFar = Math.max(maxSoFar,
currentMax);
}
return maxSoFar;
}
✅ Time: O(n)
✅
Space: O(1)
✅
Elegant and powerful
🔍 How It Works
Kadane’s Algorithm keeps track of:
At every step, you decide:
“Should I continue with current subarray or start new from
this element?”
🚀 Real Interview
Challenge #1: Track the Subarray Itself
public
static void maxSubarrayWithRange(int[] arr) {
int maxSoFar = arr[0], currentMax = arr[0];
int start = 0, end = 0, tempStart = 0;
for (int i = 1; i < arr.length; i++) {
if (arr[i] > currentMax + arr[i]) {
currentMax = arr[i];
tempStart = i;
} else {
currentMax += arr[i];
}
if (currentMax > maxSoFar) {
maxSoFar = currentMax;
start = tempStart;
end = i;
}
}
System.out.println("Max Sum: " +
maxSoFar);
System.out.println("Subarray: " +
Arrays.toString(Arrays.copyOfRange(arr, start, end + 1)));
}
✅ Outputs both sum and subarray
range
🧠 Edge Cases
Input |
Output |
Notes |
[1, 2, 3, 4] |
10 |
Whole array |
[-5, -2, -1, -3] |
-1 |
Just the least negative number |
[0, 0, 0, 0] |
0 |
Valid zero-sum |
[1, -2, 3, 4, -1] |
7 |
Mixed values |
🧨 Interview Variants
✅ Summary
Approach |
Time |
Space |
Use Case |
Brute Force |
O(n²) |
O(1) |
Small arrays |
Kadane’s |
O(n) |
O(1) |
Efficient and preferred |
Track Subarray |
O(n) |
O(1) |
If range is also needed |
Because
they test core programming logic, data handling, loops, and algorithm
efficiency.
int[] is a primitive array; Integer[] is an array of objects (wrappers). The latter allows null values and works with collections.
For fixed-size problems, use arrays. For dynamic data, ArrayList is better — but stick to arrays unless otherwise asked
Index out of bounds, mutating arrays while iterating, and forgetting that Java arrays have fixed size.
Use a Set for uniqueness or sort the array first and remove duplicates in-place using two pointers.
It’s great for sorted arrays, especially for problems involving pair sums, removing duplicates, and reversing data in-place.
Use reversal techniques or cyclic replacements to do it in O(1) space.
Linear search = O(n); binary search = O(log n), but only on sorted arrays.
Always consider edge cases: empty arrays, one element, all duplicates, etc. Optimize with hashmaps or prefix sums where needed.
Use Arrays.sort(), System.arraycopy(), Arrays.toString(), and Collections when applicable — but show the manual solution first in interviews.
Please log in to access this content. You will be redirected to the login page shortly.
LoginReady to take your education and career to the next level? Register today and join our growing community of learners and professionals.
Comments(0)