divide&conquer:find max array

时间:2023-03-08 16:55:22

package max_subarrayy;
import java.lang.Math;
public class max_subarrayy {
private static int[] array;
public static class mark{
private int lom = 100;
private int him;
private int value;
public mark(int a,int b,int c){
lom = a;him = b;value = c;
}
}
public static mark merge(int low,int high){ //return max line
int N = high + low ; // should plus when to get the mid number *high-low,high
double mid = (double)N/2;
if(low == high){return new mark(low,high,array[low]);}
mark leftmax = merge(low,(int)Math.floor(mid));
mark rightmax = merge((int)Math.floor(mid)+1,high);//even number error *Math ceil
mark midmax = findmidmax(low,high,(int)Math.floor((float)N/2));
int k = (Math.max(leftmax.value, rightmax.value) > midmax.value) ? Math.max(leftmax.value, rightmax.value) : midmax.value;
if(k == leftmax.value){return leftmax;}
else if(k == rightmax.value){return rightmax;}
else{return midmax;}

}
public static mark findmidmax(int low,int high,int mid){
int max = array[mid] + array[mid + 1];
int temp = max;
int lom = mid;
int him = mid +1;
for(int i = mid -1;i >= low;i--){
temp = temp + array[i];
if(temp > max){
max = temp;
lom = i;
}
}
temp = max;
for(int i = mid +2;i <= high;i++){// plus 2 *mid +1
temp = temp + array[i];
if(temp > max){
max = temp;
him = i;
}
}
return new mark(lom,him,max);
}

public static void main(String[] args){
int N = args.length;
array = new int[N];
for(int i = 0;i < N;i++){
array[i] = Integer.parseInt(args[i]);
}
mark a = merge(0,N-1);
System.out.println(a.lom + " " + a.him +" " + a.value);
}

}