Directly on the code bar:
Case one: all non-negative integers, in fact, the negative real processing is the same.
Package person;
Import Java.util.Scanner;
public class Main
{
public static final int maxn = 105;
public static int[] Arr = new INT[MAXN];
public static void Main (string[] args)
{
int N;
Scanner cin = new Scanner (system.in);
N = Cin.nextint ();
for (int i = 0; i < N; i++)
{
Arr[i] = Cin.nextint ();
}
int thissum,maxsum;
thissum = maxsum = 0;
for (int i = 0; i < N; i++)
{
Thissum + = arr[i];//to the right
if (Thissum > Maxsum)
{
maxsum = thissum;//Update maximum value
}
else if (Thissum < 0)
{
Thissum = 0;//If less than 0, it is impossible to be the back part and increase, discard it.
}
}
System.out.println (maxsum);
}
}
Situation two: Unsure what type of number is in the inside.
Start with the following:
1. Iterate through the array, if all is negative, find the maximum negative number, and output it to end the program, otherwise, go to the following steps.
2. The idea is the same as above.
The code is implemented as follows: (assuming all numbers are integers)
Package person;
Import Java.util.Scanner;
public class Main
{
public static final int maxn = 105;
public static int[] Arr = new INT[MAXN];
public static void Main (string[] args)
{
int N;
Scanner cin = new Scanner (system.in);
N = Cin.nextint ();
int Max = 0;
for (int i = 0; i < N; i++)
{
Arr[i] = Cin.nextint ();
if (i = = 0)
{
Max = Arr[i];
}
Else
{
Max = Math.max (Max,arr[i]);
}
}
if (Max < 0)
{
System.out.println (Max);
Return
}
This is a watershed.
int thissum,maxsum;
thissum = maxsum = 0;
for (int i = 0; i < N; i++)
{
Thissum + = arr[i];//to the right
if (Thissum > Maxsum)
{
maxsum = thissum;//Update maximum value
}
else if (Thissum < 0)
{
Thissum = 0;//If less than 0, it is impossible to be the back part and increase, discard it.
}
}
System.out.println (maxsum);
}
}
Code is actually very simple, if you do not understand, feel free to leave a message, 24 hours online, thank you
java.--maximum subsequence and (provided that all are non-negative)