Array Question 6

Home / Java Practice Question / Array Question 6

Array Question 6


Question 6. Write a Program find the subarray with the largest sum and return its sum.

Program- 


class Solution {

    public int maxSubArray(int[] nums) {     

        int currentSum=0;

        int maxSum = Integer.MIN_VALUE;

        for(int i=0;i<nums.length;i++){

            currentSum = currentSum+nums[i];

            if(currentSum > maxSum){

                maxSum = currentSum;

            }

            if(currentSum < 0){

                currentSum = 0;

            }

        }

        return maxSum;

    }

}