Java Solution to max subarray


  • 0
    P
    class Solution {
        public int maxSubArray(int[] nums) {
            
            int sum = nums[0];
            
            //if array just have one digit return the digit.
            if (nums.length==1){
                return nums[0];
            } 
            
            
            // start loop from first element.
            for (int i=0;i<nums.length;i++){
                int first = nums[i];
                
                if (first>sum){
                    sum=first;
                }            
                
                for (int j=i+1;j<nums.length;j++){
                     first = first + nums[j];
                    if (sum<first){
                        sum=first;
                    }                                
                }
                
            }
            
            return sum;
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.