>讓我們學習如何使用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中文網其他相關文章!