>让我们学习如何使用java中的kadane算法有效地找到最大子阵列总和。
问题语句:
给定尺寸n的数组,编写一个Java程序,以确定使用Kadane算法的连续子阵列的最大总和。
>示例:
<code>Input: n = 5 arr[] = 1, 2, 3, -2, 5 Output: Maximum Subarray sum is: 9</code>
了解Kadane的算法:
步骤:
>初始化两个变量:
到0和currentSum
到最小的整数值(例如,maxSum
)。currentSum
>
maxSum
Integer.MIN_VALUE
>
arr[i]
currentSum
和maxSum
>。maxSum
>。
maxSum
currentSum
表明包括先前的元素不会造成更大的总和;最好从当前元素启动一个新的子阵列。currentSum
currentSum
currentSum
>输出(示例):
<code class="language-java">import java.util.Scanner; public class KadaneAlgo { public static int findMaxSubArraySum(int[] arr, int n) { int currentSum = 0; int maxSum = Integer.MIN_VALUE; // Initialize to the smallest possible integer for (int i = 0; i < n; i++) { currentSum += arr[i]; maxSum = Math.max(maxSum, currentSum); // Update maxSum if necessary if (currentSum < 0) { currentSum = 0; // Reset currentSum if it becomes negative } } return maxSum; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter the size of the array: "); int n = scanner.nextInt(); int[] arr = new int[n]; System.out.print("Enter the elements of the array: "); for (int i = 0; i < n; i++) { arr[i] = scanner.nextInt(); } int maxSum = findMaxSubArraySum(arr, n); System.out.println("Maximum Subarray sum is: " + maxSum); scanner.close(); } }</code>
以上是Java中的最大子阵列总和:Kadane的算法的详细内容。更多信息请关注PHP中文网其他相关文章!