How to find the subarray with maximum sum of elements?

40 views Asked by At

I am trying to solve the problem where one needs to find the sum of a subarray such that the sum is maximum. Here is the Leetcode Problem. I have tried to solve the problem using brute force method. 200/210 test cases run fine. If I want to continue to solve the problem using bruit force method, what changes do I need to make to the code. Or the brute force solution will simply not work?

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

       for(int i=1; i<=nums.length; i++){
           for(int j=0; j<=nums.length-i; j++){
               int sum=0;
               for(int k=j; k<j+i; k++){
                   // Sum of Subarray
                   sum=sum+nums[k];
               }
               if(sum>finalSum){
                   finalSum=sum;
               }
           }

       }

       return finalSum; 
    }
}
1

There are 1 answers

0
Computer Dream On

You can use kadane's algorithm.