Skip to main content

My First Week in India: Expectations vs. Reality

My First Week in India: Expectations vs. Reality My First Week in India: Expectations vs. Reality Arriving in a new country is always a mix of excitement and apprehension. As I embarked on my journey to India, I had a set of expectations based on research, stories, and stereotypes. My first week in India has been a whirlwind of experiences that have both aligned with and diverged from my expectations. Here’s a comparison of what I anticipated versus what I actually encountered. Expectations Warm and Humid Weather: I expected the weather to be consistently warm and humid, as is often depicted in travel blogs and movies. Spicy Food: I anticipated a diet heavily spiced with rich and diverse flavors, given India’s renowned culinary reputation. Cultural Festivities: I was excited to witness vibrant cultural festivals and traditional celebrations throughout the year. ...

53. Maximum Subarray | Kadane’s Algorithm

53. Maximum Subarray

 Medium
Topics: Array, Dynamic Programming

💬 Problem Statement:

Given an integer array nums, find the subarray with the largest sum, and return its sum.


🧪 Examples:

Example 1:

Input: nums = [-2,1,-3,4,-1,2,1,-5,4]  
Output: 6  
Explanation: The subarray [4,-1,2,1] has the largest sum 6.

Example 2:

Input: nums = [1]  
Output: 1  
Explanation: The subarray [1] has the largest sum 1.

Example 3:

Input: nums = [5,4,-1,7,8]  
Output: 23  
Explanation: The subarray [5,4,-1,7,8] has the largest sum 23.

🔒 Constraints:

  • 1 <= nums.length <= 10⁵

  • -10⁴ <= nums[i] <= 10⁴


🧠 Approach 1: Kadane's Algorithm (O(n) Time)

Kadane’s Algorithm helps you find the maximum sum of a contiguous subarray in just one pass.

👉 Intuition:

We move through the array and:

  • Keep adding elements to a running sum (maxEndingHere)

  • If maxEndingHere becomes negative, we reset it to 0

  • Track the maximum seen so far in maxSoFar
     

MY solution,
🪄 Java Code:
 

 class Solution {
    public int maxSubArray(int[] nums) {
        int currentSum = nums[0];
        int maxSum = nums[0];

        for (int i = 1; i < nums.length; i++) {
            // Either start a new subarray at nums[i], or extend the previous one
            currentSum = Math.max(nums[i], currentSum + nums[i]);
            maxSum = Math.max(maxSum, currentSum);
        }

        return maxSum;
    }
}




🪄 Java Code:


public class Solution {
    public int maxSubArray(int[] nums) {
        int maxSoFar = Integer.MIN_VALUE;
        int maxEndingHere = 0;

        for (int num : nums) {
            maxEndingHere += num;
            if (maxSoFar < maxEndingHere) {
                maxSoFar = maxEndingHere;
            }
            if (maxEndingHere < 0) {
                maxEndingHere = 0;
            }
        }
        return maxSoFar;
    }
}

 


import java.util.ArrayList;

class Solution {
    public int findMinDiff(ArrayList<Integer> arr, int m) {
        // If the number of packets is less than the number of students, return -1
        if (arr.size() < m) {
            return -1;
        }

        // Sort the array to bring similar values together
        arr.sort(null);

        int minDiff = Integer.MAX_VALUE;

        // Use a sliding window to find the minimum difference
        for (int i = 0; i + m - 1 < arr.size(); i++) {
            int diff = arr.get(i + m - 1) - arr.get(i);
            minDiff = Math.min(minDiff, diff);
        }

        return minDiff;
    }
}
 
 

🔍 Dry Run (for nums = [-2, 1, -3, 4, -1, 2, 1]):

Index num maxEndingHere maxSoFar
0 -2 -2 → reset to 0 -2
1 1 1 1
2 -3 -2 → reset to 0 1
3 4 4 4
4 -1 3 4
5 2 5 5
6 1 6 6 ✅

Final result: 6


📈 Time & Space Complexity:

  • Time: O(n)

  • Space: O(1)


🔁 Follow-Up:

Try solving it using Divide and Conquer, which gives O(n log n) time complexity. It’s more complex but good for understanding recursive problem-solving.


Let me know if you want to include the divide and conquer version too!


💡 What is Kadane’s Algorithm?

Kadane’s Algorithm is used to find the maximum sum of a contiguous subarray in an array.
This problem is also known as the "Maximum Subarray Problem."


Example:
Input: [-2, 1, -3, 4, -1, 2, 1, -5, 4]
Output: 6 → (The subarray [4, -1, 2, 1] has the maximum sum 6)


🧠 Why Kadane’s Algorithm?

You could solve this using brute force by checking all possible subarrays and calculating their sums.
But that would take O(n²) time — very slow for large inputs.

Kadane’s Algorithm does it in O(n) time by cleverly keeping track of:

  • Current sum of the subarray (maxEndingHere)

  • Maximum sum seen so far (maxSoFar)


🔍 Step-by-step Explanation

Let’s say we have this array:

Index:         0   1   2   3   4   5   6
Array:        [-2, 1, -3, 4, -1, 2, 1]

Step 1: Initialization

  • maxEndingHere = 0 → stores the sum ending at the current position

  • maxSoFar = Integer.MIN_VALUE → tracks the highest sum so far

Step 2: Loop through each element:

For each element num in array:

maxEndingHere += num;
if (maxSoFar < maxEndingHere)
    maxSoFar = maxEndingHere;
if (maxEndingHere < 0)
    maxEndingHere = 0;

Step 3: How it works with the example:

i num maxEndingHere (sum so far) maxSoFar (max sum)
0 -2 -2 → reset to 0 -2
1 1 1 1
2 -3 -2 → reset to 0 1
3 4 4 4
4 -1 3 4
5 2 5 5
6 1 6 6 ✅

So, max sum is 6.


📌 Final Code in Java



public class KadaneAlgorithm {
    public static int maxSubArray(int[] nums) {
        int maxSoFar = Integer.MIN_VALUE;
        int maxEndingHere = 0;

        for (int num : nums) {
            maxEndingHere += num;
            if (maxSoFar < maxEndingHere) {
                maxSoFar = maxEndingHere;
            }
            if (maxEndingHere < 0) {
                maxEndingHere = 0;
            }
        }
        return maxSoFar;
    }

    public static void main(String[] args) {
        int[] nums = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
        System.out.println("Maximum Subarray Sum: " + maxSubArray(nums));
    }
}


✅ When to Reset maxEndingHere?

If maxEndingHere becomes negative, we reset it to 0.
Why? Because a negative sum will only reduce the total sum of the next subarray.


⚡ Time and Space Complexity:

  • Time Complexity: O(n) → only one pass

  • Space Complexity: O(1) → no extra space needed



Comments

Popular posts from this blog

How to Crack College Placements: A Complete Guide to Projects, Interviews, and Success

How to Crack College Placements: A Complete Guide to Projects, Interviews, and Success How to Crack College Placements: A Complete Guide to Projects, Interviews, and Success Welcome to the first episode of The Mali Show ! If you're a student preparing for college placements , you're probably feeling both excited and nervous. Landing that dream job or internship is a big deal, but with the right approach, cracking campus placements doesn’t have to be a stressful experience. In this blog post, we’ll break down everything you need to know about how to crack college placements , from selecting the perfect placement projects to preparing for those nerve-wracking interviews . With these tips, you’ll be one step closer to success. 1. How to Crack College Placements: The Basics When it comes to college placements , understanding the entire process is key. Every college has its own str...

Momo Origin, recipes,photo and challange

Momo Origin, recipes,photo and challange Last time, in the month of may i went home after the 7 months. Luckily i went home to my meet my parents.   So I tested my favourite snacks, that is the Momo. YouTube vlog    Momo are bite- size dumplings made with a spoonful of stuffing wrapped in dough. Momo are generally fumed, though they're occasionally fried or brume- fried. Meat or vegetables paddings becomes succulent as it produces an intensely seasoned broth sealed inside the wrappers. Variants of the dish developed latterly in Nepal after it came popular among Asians.Eating dumplings on the first day of the new time was a extensively spread custom in northern China. Written records show that dumplings came popular during the Southern and Northern dynasties( 420 – 589 announcement)., the foremost exhumed real dumplings were set up in Astana Cemetery dated between 499 announcement and 640 announcement. Momo are so delicious and the recipes is also simple....

33. Search in Rotated Sorted Array

 33. Search in Rotated Sorted Array 📄 Problem Statement : There is an integer array nums sorted in ascending order (with distinct values). Before being passed to your function, nums may be rotated at an unknown pivot index k (where 1 <= k < nums.length ) such that the array becomes [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] . You are given the array nums after the rotation and an integer target . Your task is to return the index of the target if it exists in nums , or return -1 if it does not exist. You must solve it in O(log n) time. 📚 Examples : Example 1 : Input: nums = [4,5,6,7,0,1,2], target = 0 Output: 4 Example 2 : Input: nums = [4,5,6,7,0,1,2], target = 3 Output: -1 Example 3 : Input: nums = [1], target = 0 Output: -1 📜 Constraints : 1 <= nums.length <= 5000 -10⁴ <= nums[i] <= 10⁴ All values of nums are unique . nums is a sorted array, possibly rotated . -10⁴ <= target <= 10⁴ ...