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.

12 afișări0 comentarii

Postări recente

Afișează-le pe toate

Weighted Job Scheduling in JAVA

You receive a list of jobs that have three elements: start time, finish time and profit. You have to schedule the jobs with no overlapping, in order to obtain the maximum profit. Solution: 1. static

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 vertically 2 x 1 or horizontally as 1 x 2. Solution: 1. static

bottom of page