A cloud computing company can accommodate various requirements for resources. The company system runs two servers. For load balancing purposes, the load of the resources gets transferred to the servers one by one. Initially, the first request goes to server 1, the next request goes to server 2, and so on. The requests served by the servers are of two types i.e. one for memory allocation(denoted by a positive number) and the other for memory deallocation (denoted by a negative number).
Write an algorithm to find the total number of units of memory allocated/deallocated by the server 1 after processing all the requests.
Input
The first line of the input consists of an integer req_size, representing the number of requests (N).
The second line consists of N space-separated integers – req1, req2,….. , reqN, representing the requests for the allocation/deallocation of the respective memory units.
Output
Print an integer representing the total number of units of memory allocated/deallocated by the server 1 after processing all the requests.
Constraints
0 ≤ req_size ≤ 105
-106 ≤ reqi ≤ 106
1 ≤ i ≤ req_size
Example
Input:
7
2 -3 8 -6 -7 18 1
Output:
4
Explanation:
The requests served by server 1 are [2,8,-7,1].
Therefore, the total number of memory units allocated/released by server 1 is 4.
Solution
import java.util.*;
import java.lang.*;
import java.io.*;
public class Solution
{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
//input for req
int req_size = in.nextInt();
int req[] = new int[req_size];
for(int idx = 0; idx < req_size; idx++)
{
req[idx] = in.nextInt();
}
int result = memServer1(req);
System.out.print(result);
}
public static int memServer1(int[] req)
{
int answer = 0;
// Write your code her
int count = 0;
for(int i = 0; i < req.length; i++){
if(count % 2 == 0){
if(req[i] > 0){
answer += req[i];
}
}
count++;
}
return answer;
}
}
Happy Learning – If you require any further information, feel free to contact me.