Question:
How to find the largest sum subarray size at subsequent level using Java

Summary

This is the maxSumWithK method. Using a given array an of length n, this method determines the maximum possible sum of a subarray of length k.


Solution

//User function Template for Java



class Solution {

    

    public long maxSumWithK(long a[], long n, long k)

    {

        long sum = 0;

        long maxSum = 0;

        long prevElemSum = 0;

        

        for (int i = 0; i < k; i++) {

            sum = sum + a[i];

        }

        maxSum = sum;

        int m = 0;

        

        for(int i = (int)k; i < n; i++){

            sum = sum + a[i];

            maxSum = Math.max(sum, maxSum);

            prevElemSum = prevElemSum + a[m++];

            

            if(prevElemSum < 0){

                sum = sum - prevElemSum;

                prevElemSum = 0;

                maxSum = Math.max(sum, maxSum);

            }

        }

        

        return maxSum;

    }

}


Explanation

  • The Solution class contains a declaration for the maxSumWithK method. 

  • An array of large numbers is called a[].

  • n: The array's length a. k: The subarray's length for which the maximum sum must be computed.

  • sum: A variable used to record the current subarray's sum.

  • maxSum: A variable used to hold the highest sum discovered to date.

  • Using a for loop, the code determines the initial sum of the array's first k elements.


Answered by:> >imajaythacmoi

Credit:> >GeekforGeeks


Suggested blogs:

>Calculating the Nth Fibonacci Number

>How to clone an undirected graph using Java

>Check if strings are rotations of each other or not with Java

>How to Detect cycle in an undirected graph with Java?

>How to check whether all leaves are at the same level using Java

>Compute amount of water that can trapped between the blocks using Java


Submit
0 Answers

What Our Clients Say About Us

Client satisfaction is our ultimate goal. Here are some kind words of our precious clients they have used to express their satisfaction with our service.

Why Choose Us ?

We endow businesses with flexible engagement models based on their unique needs. Our strength lies in state-of-the-art technology and affordable consulting services. Try us for fast POCs, full-fledged applications, or technology consulting. Always available for your service.