top of page
Caută
Poza scriitoruluioanaunciuleanu

Largest Sum Contiguous Subarray (Kadane's Algorithm) in JAVA

Given an integer array, you have to find a contiguous subarray with the largest sum, and return that sum.


Input: int[] inputArray = {-1, -5, 4, 0, -3, 2, 6, -1}; Output: 9 Explanation: The contiguous subarray with the largest sum is: 4, 0, -3, 2, 6.



Solution:


1. public static int maxSubArray(int[] inputArray) { 2. int currentSubArray = inputArray[0]; 3. int maxSubArray = inputArray[0]; 4. 5. for (int i = 1; i < inputArray.length; i++) { 6. int currentNumber = inputArray[i]; 7. currentSubArray = Math.max(currentNumber, currentSubArray + currentNumber); 8. maxSubArray = Math.max(maxSubArray, currentSubArray); 9. } 10. 11. return maxSubArray; 12. } 13.

13 afișări0 comentarii

Postări recente

Afișează-le pe toate

Tiling Problem in JAVA

You can use a board that is 2 x n size. The tiles are of size 2 x 1. Count the number of ways to tile the board. Tiles can be placed...

Comments


bottom of page