ThinkVireo
  • Home (current)
  • About
  • TCS IPA/DCA(new)
    TCS DCA TCS IPA Python TCS IPA JAVA
  • FAQs
    TCS 2025
  • Contact
  • India
  • Leetcode

Max and Subarray

    Question: Given an array of integers, find the subarray that has the maximum sum and return its sum.
    For example, given the array [-2, 1, -3, 4, -1, 2, 1, -5, 4],
    the subarray with the maximum sum is [4, -1, 2, 1],
    and its sum is 6.

    Write a Java function with the following signature to solve the problem:
    The function should take an integer array nums as input and return an integer, which is the sum of the maximum sum subarray.
    Note: The subarray should have at least one element.
    Hint: You can use the Kadane's algorithm to solve this problem in linear time complexity.

    Sample Input:
    Sample Output:
    6

    1. JAVA Code:
      
          public static int maxSubarraySum(int[] nums) {
              int maxSum = nums[0];
              int currentSum = nums[0];
          
              for (int i = 1; i < nums.length; i++) {
                  currentSum = Math.max(nums[i], currentSum + nums[i]);
                  maxSum = Math.max(maxSum, currentSum);
              }
          
              return maxSum;
          }
          
          
                  


    Shubham Shrivas


ThinkVireo

ThinkVireo

TCS IPA Leetcode Python Java Partners Careers
FAQ Contact About Support Blog Services
Privacy & Policy

©ThinkVireo 2025 . All rights reserved.