Without Adjacent: Given an array arr[] of N positive integers. The task is to find a subsequence with maximum sum such that there should be no adjacent elements from the array in the subsequence.
Without Adjacent Contest
Input:
First line of input contains number of testcases T. For each testcase, first line of input contains size of array N. Next line contains N elements of the array space seperated.
Output:
For each testcase, print the maximum sum of the subsequence.
Constraints:
1 <= T <= 100
1 <= N <= 106
1 <= arr[i] <= 106
Example:
Input:
2
3
1 2 3
3
1 20 3
Output:
4
20
Explanation:
Testcase 1: Elements 1 and 3 form a subsequence with maximum sum and no elements in the subsequence are adjacent in the array.
Testcase 2: Element 20 from the array forms a subsequence with maximum sum.
Solution:
import java.util.*;
import java.lang.*;
import java.io.*;
public class WithoutAdjacent {
static class FastReader{
BufferedReader br;
StringTokenizer st;
public FastReader(){
br = new BufferedReader(new InputStreamReader(System.in));
}
String next(){
while (st == null || !st.hasMoreElements()){
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
String nextLine(){
String str = "";
try {
str = br.readLine();
}catch (IOException e){
e.printStackTrace();
}
return str;
}
int nextInt(){
return Integer.parseInt(next());
}
}
static int findSubArrayWithMinSum(int[] arr, int i , int j){
int min = Integer.MIN_VALUE;
int maxElement = arr[0];
for (int k = 0; k < j; k++) {
int currSum = arr[k];
maxElement = Math.max(maxElement,arr[k]);
for (int l = k+2; l < j; l+=2) {
currSum+=arr[l];
}
min = Math.max(currSum,min);
}
return Math.max(min,maxElement);
}
public static void main(String[] args) {
FastReader fr = new FastReader();
int t = fr.nextInt();
while (t-->0){
int n = fr.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = fr.nextInt();
}
long x = arr[0];
long y = 0;
long res;
for(int i=1;i<n;i++)
{
res = Math.max(x, y);
x = y + arr[i];
y = res;
}
System.out.println((long)Math.max(x,y));
}
}
}
def withoutAdjacent(arr):
incl = 0
excl = 0
for i in arr:
# Current max excluding i (No ternary in
# Python)
new_excl = excl if excl>incl else incl
# Current max including i
incl = excl + int(i)
excl = new_excl
# return max of incl and excl
return (excl if excl>incl else incl)
if __name__ == '__main__':
t = int(input())
for c in range(t):
N = int(input())
arr = input().strip().split()
print (withoutAdjacent(arr))
Happy Learning – If you require any further information, feel free to contact me.