In an interview I was asked to solve the following problem:
find a subarray with max sum
I have written a piece of code for the same. I need your help in reviewing this code.
package com.ankit.rnd;
public class MaxSubArrSum {
int largestSum=0;
int previousLargestSum=0;
public static void main(String[] args) {
// int [] array = {-2,1,-3,4,-1,2,1,-5,4};
int [] array = {-5,1,-3,7,-1,2,1,-4,6};
// int [] array = {-2,-3,-4,2};
MaxSubArrSum obj = new MaxSubArrSum();
for(int varindex=0;varindex<array.length;varindex++){
// int sumis =new MaxSubArrSum().findSum(varindex,array);
// System.out.println("sumis::" +sumis);
obj.splitCurrentArray(varindex,array);
}
}
private void splitCurrentArray(int in, int[] arr) {
int [] tempArr = new int[arr.length-in];
for(int i=in;i<arr.length;i++){
if(in ==0){
tempArr[i] = arr[i];
}
else{
tempArr[i-in] = arr[i];
}
}
int sum =findSum(in, tempArr);
System.out.println("Previous Largest Sum::" + previousLargestSum);
System.out.println("Largest Sum found:" + sum);
}
@SuppressWarnings("unused")
private int findSum(int start,int [] array) {
int[] currentArray ={};
int [] largestArray = new int[array.length];
int sum=0;
/*for(int i=start;i<array.length;i++){*/
for(int i=0;i<array.length;i++){
//a little inefficient here as it always create an array with size more than total number of elements that should be there in the temp array.
int psuedoIndex=i;
if(start==0){
currentArray = new int[i + 1];
for (int j = 0; j <= i; j++) {
currentArray[j] = array[j];
psuedoIndex=psuedoIndex+1;
}
}
else {
currentArray = new int[i+1];
for (int j = 0; j <= i; j++) {
currentArray[j] = array[j];
/*
* if(psuedoIndex == array.length){ //needs a fix. as we
* have reached the end of the array. //currentArray[j] =
* array[psuedoIndex-1]; currentArray[j] = 0; break; } else{
*
* currentArray[j] = array[psuedoIndex]; is commented out
* because it missed the element in the previous array.
*
*
* //currentArray[j] = array[psuedoIndex]; currentArray[j] =
* array[j]; }
*/
psuedoIndex=psuedoIndex+1;
}
}
if((sum = calculate(currentArray))>largestSum){
previousLargestSum=largestSum;
largestSum=sum;
for(int k=0;k<currentArray.length;k++){
System.out.print(currentArray[k] + "|");
}
System.out.println("");
}
}
return largestSum;
}
private int calculate(int [] currentArr){
int sumOfElements =0;
for(int index=0;index<currentArr.length;index++){
sumOfElements +=currentArr[index];
}
//System.out.println("sum is:" + sumOfElements);
return sumOfElements;
}
}