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.
Comments