🍑 算法题解专栏
输入
2
5 6 -1 5 4 -7
7 0 6 -1 1 -6 7 -5
输出
Case 1:
14 1 4
Case 2:
7 1 6
🙈 输出换行优先使用 println
⭐ \n:回车的转义符
⭐ %d:格式化字符( 用于printf )
🤠 线性DP + 神奇的输出
🍑 f[ i ] 表示以第 i 个数结尾的最大和
🥚 关于 %n 格式
🍑 代码实现
import java.util.Arrays;
import java.util.Scanner;
public class Main
{
static int N = 100010;
static int[] a = new int[N];
static int[] f = new int[N];
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
for (int i = 1; i <= T; i++)
{
int n = sc.nextInt();
for (int j = 1; j <= n; j++)
a[j] = sc.nextInt();
int r = 1;
Arrays.fill(f, 0);
for (int j = 1; j <= n; j++)
{
if (f[j - 1] > 0)
f[j] = a[j] + f[j - 1];
else
{
f[j] = a[j];
}
if (f[j] > f[r])
{
r = j;
}
}
// System.out.println(res + " " + idx);
// System.out.print("Case " + i + ":\n" + f[r] + " ");
int l = r-1;
while(l >= 1 && f[l] >= 0)
{
l--;
}
/*
//输出格式测试
System.out.println("版本1");
System.out.printf("Case %d:\n%d %d %d\n",i,f[r],l+1,r); //PE
// System.out.printf("Case %d:%n%d %d %d%n",i,f[r],l+1,r); //PE
System.out.println("版本2");
System.out.print("Case " + i + ":\n" + f[r] + " " + (l+1) + " " + r + "\n"); //PE
System.out.println("版本3");
*/
//AC1
System.out.println("Case " + i + ":");
System.out.println(f[r] + " " + (l+1) + " " + r) ;
//AC2
// System.out.printf("Case %d:%n",i);
// System.out.printf("%d %d %d%n",f[r],l+1,r);
if(i != T)
System.out.println();
}
}
}
🍑 输出格式测试
版本1
Case 1:
14 1 4
版本2
Case 1:
14 1 4
版本3
Case 1:
14 1 4
版本1
Case 2:
7 1 6
版本2
Case 2:
7 1 6
版本3
Case 2:
7 1 6
🍑 参考大佬的版本(原文找不到了)
import java.util.Arrays;
import java.util.Scanner;
public class Main
{
static int N = 100010;
static int[] f = new int[N];
static int[] a = new int[N];
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
for (int i = 1; i <= T; i++)
{
int n = sc.nextInt();
for (int j = 1; j <= n; j++)
a[j] = sc.nextInt();
Arrays.fill(f, 0);
int l = 1;
int r = 1;
int start = 1;
int max = a[1];
f[1] = a[1];
for (int j = 2; j <= n; j++)
{
if (f[j - 1] >= 0)
f[j] = f[j - 1] + a[j];
else
{
f[j] = a[j];
// 顺便更新起点
start = j;// 抛弃 j 前边的所有数
}
if (f[j] > max)
{
max = f[j];
l = start;
r = j;
}
}
System.out.println("Case " + i + ":");
System.out.println(max + " " + l + " " + r) ;
if (i != T)
System.out.println();
}
}
}