Java实现三种算法实现最大字段和问题并用文件存储
时间: 2024-03-26 21:35:36 浏览: 54
好的,以下是Java实现三种算法实现最大子段和问题并用文件存储的示例代码:
```java
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;
public class MaxSubarray {
/**
* 动态规划算法实现最大子段和
* @param nums 整数数组
* @return 最大子段和
*/
public static int maxSubarrayDP(int[] nums) {
int maxSum = nums[0];
int curSum = nums[0];
for (int i = 1; i < nums.length; i++) {
curSum = Math.max(nums[i], curSum + nums[i]);
maxSum = Math.max(maxSum, curSum);
}
return maxSum;
}
/**
* 分治算法实现最大子段和
* @param nums 整数数组
* @return 最大子段和
*/
public static int maxSubarrayDC(int[] nums) {
return maxSubarrayDC(nums, 0, nums.length - 1);
}
private static int maxSubarrayDC(int[] nums, int left, int right) {
if (left == right) {
return nums[left];
}
int mid = (left + right) / 2;
int maxLeftSum = maxSubarrayDC(nums, left, mid);
int maxRightSum = maxSubarrayDC(nums, mid + 1, right);
int maxCrossSum = maxCrossSubarray(nums, left, right, mid);
return Math.max(Math.max(maxLeftSum, maxRightSum), maxCrossSum);
}
private static int maxCrossSubarray(int[] nums, int left, int right, int mid) {
int maxLeftSum = Integer.MIN_VALUE;
int curSum = 0;
for (int i = mid; i >= left; i--) {
curSum += nums[i];
maxLeftSum = Math.max(maxLeftSum, curSum);
}
int maxRightSum = Integer.MIN_VALUE;
curSum = 0;
for (int i = mid + 1; i <= right; i++) {
curSum += nums[i];
maxRightSum = Math.max(maxRightSum, curSum);
}
return maxLeftSum + maxRightSum;
}
/**
* 蛮力算法实现最大子段和
* @param nums 整数数组
* @return 最大子段和
*/
public static int maxSubarrayBF(int[] nums) {
int maxSum = Integer.MIN_VALUE;
for (int i = 0; i < nums.length; i++) {
int curSum = 0;
for (int j = i; j < nums.length; j++) {
curSum += nums[j];
maxSum = Math.max(maxSum, curSum);
}
}
return maxSum;
}
/**
* 将结果写入文件
* @param fileName 文件名
* @param content 内容
*/
public static void writeToFile(String fileName, String content) {
FileWriter writer = null;
try {
writer = new FileWriter(new File(fileName));
writer.write(content);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
int[] nums = {1, -2, 3, 10, -4, 7, 2, -5};
int maxSumDP = maxSubarrayDP(nums);
int maxSumDC = maxSubarrayDC(nums);
int maxSumBF = maxSubarrayBF(nums);
String content = "原数组:" + Arrays.toString(nums) + "\n"
+ "动态规划算法结果:" + maxSumDP + "\n"
+ "分治算法结果:" + maxSumDC + "\n"
+ "蛮力算法结果:" + maxSumBF + "\n";
writeToFile("max_subarray.txt", content);
System.out.println("计算完成,结果已写入文件 max_subarray.txt");
}
}
```
这段代码实现了动态规划、分治和蛮力三种算法求解最大子段和问题,并将结果写入文件 max_subarray.txt 中。您可以将这段代码保存为 MaxSubarray.java 文件并在命令行中执行,或在集成开发环境中运行它。
阅读全文