-
Notifications
You must be signed in to change notification settings - Fork 2
/
Even Odd Sum
70 lines (53 loc) · 1.38 KB
/
Even Odd Sum
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
PROBLEM:-
Given an array Arr[] of N integers.Find the sum of values of even and odd index positions separately.
Example 1:
Input:
N=5
Arr={1,2,3,4,5}
Output:
9 6
Explanation:
The sum of elements at odd places i.e
at 1st,3rd and 5th places are (1+3+5=9)
Similarly,the sum of elements at even
places i.e. at 2nd and 4th places are
(2+4=6).
Example 2:
Input:
N=5
Arr={1,1,1,1,1}
Output:
3 2
Explanation:
The sum of elements at odd places
is (1+1+1=3).Similarly, the sum of
elements at even places is (1+1=2)
Your Task:
You don't need to read input or print anything.Your Task is to complete the function EvenOddSum() which takes an integer N and an array Arr as input parameters and returns the sum of elements in odd places and in even places separately.
Expected Time Complexity:O(N)
Expected Auxillary Space:O(1)
Constraints:
1<=N<=105
0<=Arr[i]<=104,for 0<=i
SOLUTION:
JAVA CODE:
// User function Template for Java
class Solution {
ArrayList<Integer> EvenOddSum(int N, int Arr[]) {
// code here
ArrayList<Integer> list=new ArrayList<Integer>();
//ArrayList<Integer> odd=new ArrayList<Integer>();
int sum1=0,sum2=0;
for(int i=0;i<N;i=i+2)
{
sum1=sum1+Arr[i];
}
for(int j=1;j<N;j=j+2)
{
sum2=sum2+Arr[j];
}
list.add(sum1);
list.add(sum2);
return list;
}
}