In: Computer Science
Program in java
1- Implement an algorithms to calculate the sum of all numbers in an array.
2- Implement an algorithm to determine if an array has all unique integer values.
3- Given an array nums. We define a running sum of an array as runningSum[i] = sum(nums[0]…nums[i]).
Return the running sum of nums.
Example 1:
Input: nums = [1,2,3,4] Output: [1,3,6,10] Explanation: Running sum is obtained as follows: [1, 1+2, 1+2+3, 1+2+3+4].
/*If you have any query do comment in the comment section else like the solution*/
import java.util.*;
public class ArrayUtil{
public static void main(String []args){
Scanner sc = new Scanner(System.in);
System.out.print("Enter size of array : ");
int n = sc.nextInt();
int arr[] = new int[n];
for(int i=0;i<n;i++) {
arr[i] = sc.nextInt();
}
runningSum(arr, n);
if(isUnique(arr, n)) {
System.out.println("Array is unique");
} else {
System.out.println("Array is not unique");
}
}
public static void runningSum(int arr[], int n) {
int i, sum = 0;
int prefixSum[] = new int[n];
prefixSum[0] = arr[0];
for(i=1;i<n;i++) {
prefixSum[i] = arr[i] + prefixSum[i-1];
}
for(i=0;i<n;i++) {
System.out.print(prefixSum[i] + " ");
}
System.out.println();
}
public static boolean isUnique(int arr[], int n) {
int i, j;
for(i=0;i<n;i++) {
for(j=i+1;j<n;j++) {
if(arr[i] == arr[j]) {
return false;
}
}
}
return true;
}
}
Input:
1 2 3 4
Output:
1 3 6 10 Array is unique