Sunday, 16 May 2021

Maximum Subarray

 Find the contiguous subarray within an array (containing at least one number) which has the largest sum.

For example, given the array [ − 2,1, − 3,4, − 1,2,1, − 5,4], the contiguous subarray [4, − 1,2,1] has the largest sum =

6.


public class MaximumSumSubarray {

    public static void main(String[] args) {

        int[] arr = {4,3,-2,6,-14,7,-1,4,5,7,-10,2,9,-10,-5,-9,6,1};


        int maxSum =Integer.MIN_VALUE;

        int tempSum = 0;

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

            tempSum+=arr[i];


            if(tempSum<arr[i]){

                tempSum = arr[i];

            }

            maxSum = Math.max(maxSum,tempSum);

        }

        System.out.println(maxSum);

    }

}


Result: 23

No comments:

Post a Comment

links for Data Structure

  1) 𝐁𝐞𝐜𝐨𝐦𝐞 𝐌𝐚𝐬𝐭𝐞𝐫 𝐒𝐧 π‹π’π§π€πžπ 𝐋𝐒𝐬𝐭:  https://lnkd.in/gXQux4zj 2) 𝐀π₯π₯ 𝐭𝐲𝐩𝐞𝐬 𝐨𝐟 π“π«πžπž π“π«πšπ―πžπ«π¬πšπ₯𝐬...