Find Pivot Index in Java code

Find Pivot Index in Java code

There is an array, which has some integers. We have to find an index, where the sum of all numbers on the left side is equal to the sum of all numbers on the right side. If such an index does not exist, then we will return -1









class HelloWorld {
public static int pivotIndex(int[] nums) {

int totalSum = 0;

for (int num : nums) {
totalSum += num;
}

System.out.println("totalSum " + totalSum);

int leftSum = 0;
for (int i = 0; i < nums.length; i++) {
if (leftSum == totalSum - leftSum - nums[i]) {
return i;
}
leftSum += nums[i];
System.out.println("leftSum : "+ leftSum);
}
return -1;
}

public static void main(String[] args) {
int arr [] = {1,2,3,1,5};

System.out.print(pivotIndex(arr));
}
}


Output------------

totalSum 12
leftSum : 1
leftSum : 3
leftSum : 6
leftSum : 7
leftSum : 12
-1

No comments: