1、暴力枚举(复杂度n方)(java版)
// 枚举(超时)
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] arr = new int[n];
int max = 0;
int l = 0;
int r = 0;
for(int i = 0;i < n;i++){
arr[i] = sc.nextInt();
}
for(int i = 0;i < n;i++){
int sum = 0;
for(int j = i;j < n;j++){
sum += arr[j];
if(sum > max){
max = sum;
l = i + 1;
r = j + 1;
}
}
}
System.out.print(max + "\n" + l + " " + r);
}
}
2、分治递归(python版)
# 分治递归
n = int(input())
nums = list(map(int,input().split()))
def maxSum(left,right):
if left == right:
return (nums[left] if nums[left] > 0 else 0, left, left)
else:
center = (left + right) // 2
leftSum, leftStart, leftEnd = maxSum(left, center)
rightSum, rightStart, rightEnd = maxSum(center + 1, right)
s1, lefts, maxLeft = 0, 0, center
for i in range(center, left - 1, -1):
lefts += nums[i]
if lefts > s1:
s1, maxLeft = lefts, i
s2, rights, maxRight = 0, 0, center + 1
for i in range(center + 1, right + 1):
rights += nums[i]
if rights > s2:
s2, maxRight = rights, i
sum = s1 + s2
if sum >= leftSum and sum >= rightSum:
return sum, maxLeft, maxRight
elif leftSum < rightSum:
return rightSum, rightStart, rightEnd
else:
return leftSum, leftStart, leftEnd
sum, left, right = maxSum(0, n-1)
print(f"{sum}\n{left + 1} {right + 1}")
3、动态规划(python版)
# 动态规划
n = int(input())
nums = list(map(int,input().split()))
def maxSum():
sum, a, left, right, tempLeft = 0, 0, 0, 0, 0
for i in range(0, n):
a += nums[i]
if a < 0:
a, tempLeft = 0, i + 1
if a > sum:
sum,left, right = a, tempLeft, i
return sum, left, right
sum, left, right = maxSum()
print(f"{sum}\n{left + 1} {right + 1}")
4、动态规划(java版)
// 动态规划
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] nums = new int[n];
int sum = 0, a = 0, left = 0, right = 0, tempLeft = 0;
for(int i = 0;i < n;i++){
nums[i] = sc.nextInt();
a += nums[i];
if(a < 0){
a = 0;
tempLeft = i + 1;
}
if(a > sum){
sum = a;
left = tempLeft;
right = i;
}
}
System.out.println(sum + "\n" + (left + 1) + " " + (right + 1));
}
}
标签:right,最大,子段,int,sum,nums,center,方法,left
From: https://blog.csdn.net/J_R___/article/details/144832604