public int[] maxset(int[] A) {
long tempSum = 0;
long finalSum = 0;
ArrayList<Integer> maxArray = new ArrayList<>();
ArrayList<Integer> newArray = new ArrayList<>();
for(int i=0;i<A.length;i++) {
if(A[i]>=0){
tempSum = tempSum+A[i];
newArray.add(A[i]);
if(tempSum>finalSum ||( tempSum==finalSum && newArray.size()>maxArray.size())) {
finalSum = tempSum;
maxArray = (ArrayList<Integer>)newArray.clone();
}
}else {
tempSum = 0;
newArray = new ArrayList<>();
}
}
int[] list = new int[maxArray.size()];
for(int i=0;i<maxArray.size();i++) {
list[i] = maxArray.get(i);
}
return list;
}
input: int[] arr = {1967513926, 1540383426, -1303455736, -521595368};
output: [1967513926, 1540383426]
input: int[] arr = {0,0,-1,0}
output: [0,0]
long tempSum = 0;
long finalSum = 0;
ArrayList<Integer> maxArray = new ArrayList<>();
ArrayList<Integer> newArray = new ArrayList<>();
for(int i=0;i<A.length;i++) {
if(A[i]>=0){
tempSum = tempSum+A[i];
newArray.add(A[i]);
if(tempSum>finalSum ||( tempSum==finalSum && newArray.size()>maxArray.size())) {
finalSum = tempSum;
maxArray = (ArrayList<Integer>)newArray.clone();
}
}else {
tempSum = 0;
newArray = new ArrayList<>();
}
}
int[] list = new int[maxArray.size()];
for(int i=0;i<maxArray.size();i++) {
list[i] = maxArray.get(i);
}
return list;
}
input: int[] arr = {1967513926, 1540383426, -1303455736, -521595368};
output: [1967513926, 1540383426]
input: int[] arr = {0,0,-1,0}
output: [0,0]
No comments:
Post a Comment