Physical Address

304 North Cardinal St.
Dorchester Center, MA 02124

Maximum Damage CodeChef Solution

Problem -Maximum Damage CodeChef Solution

This website is dedicated for CodeChef solution where we will publish right solution of all your favourite CodeChef problems along with detailed explanatory of different competitive programming concepts and languages.

Maximum Damage CodeChef Solution in C++17

#include <iostream>
using namespace std;

int main() {
    int t;
    cin >> t;
    while (t--)
    {
        int n;
        cin >> n;
        int arr[n];
        for (int i = 0; i < n; i++)
        {
            cin >> arr[i];
        }
        for(int i = 0; i < n; i++)
        {
    	    if(i==0)
    	    {
                cout<<(arr[i]&arr[i+1])<<" "; 
    	        continue;
    	    }
    	    else if(i==n-1)
    	    {
    	        cout<<(arr[i]&arr[i-1])<<" "; 
    	    }
    	    else
    	    {
    	        int ans = max(arr[i]&arr[i-1],arr[i]&arr[i+1]); 
    	        cout<<ans<<" "; 
    	    }
	    }
	    cout<<endl; 
    }
	return 0;
}

Eidi Gift CodeChef Solution in C++14


#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define mod 1000000007
#define Time cerr << "time taken : " << (float)clock() / CLOCKS_PER_SEC << " secs" << endl;
#define pb push_back
#define mp make_pair
#define line cout << endl;
#define ff first
#define ss second
#define vi vector<int>
#define no cout << "NO" << endl;
#define yes cout << "YES" << endl;
#define printv(v)                      \
  for (int i = 0; i < (v.size()); i++) \
  {                                    \
    cout << v[i] << " ";               \
  }                                    \
  line;
#define onesbits(x) __builtin_popcountll(x)
#define zerobits(x) __builtin_ctzll(x)
#define sp(x, y) fixed << setprecision(y) << x
#define w(x) \
  int x;     \
  cin >> x;  \
  while (x--)
#define tk(x) \
  int x;      \
  cin >> x;
#define fast ios_base::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr);
#ifndef ONLINE_JUDGE
#define debug(x)     \
  cerr << #x << " "; \
  _print(x);         \
  cerr << endl;
#else
#define debug(x)
#endif
template <class T>
void _print(T t)
{
  cerr << t;
}

template <class T, class V>
void _print(pair<T, V> p)
{
  cerr << "{";
  _print(p.ff);
  cerr << ",";
  _print(p.ss);
  cerr << "}";
}

template <class T>
void _print(vector<T> v)
{
  cerr << "[ ";
  for (T i : v)
  {
    _print(i);
    cerr << " ";
  }
  cerr << "]";
}

template <class T>
void _print(vector<vector<T>> v)
{
  cerr << "[\n";
  for (int l = 0; l < v.size(); l++)
  {
    {
      for (int k = 0; k < v[l].size(); k++)
        cerr << v[l][k] << " ";
    }
    cerr << "\n";
  }
  cerr << "]";
}

template <class T, class V>
void _print(map<T, V> v)
{
  cerr << "[ ";
  for (auto i : v)
  {
    _print(i);
    cerr << " ";
  }
  cerr << "]";
}

template <class T>
void _print(set<T> v)
{
  cerr << "[ ";
  for (T i : v)
  {
    _print(i);
    cerr << " ";
  }
  cerr << "]";
}

const long long inf = 1e18;
const int MOD = 1e9 + 7;
const int MAX = 1e6;

int numbit(int x)
{
    int ans = 0;
    while (x > 0)
    {
        x = x >> 1;
        ans++;
    }
    return ans;
}

int setbit(int x)
{
    int ans = 0;
    while (x > 0)
    {
        if (x & 1)
        {
            ans++;
        }
        x = x >> 1;
    }
    return ans;
}

bool isValid(string s)
{
  int len = s.size();
  for (int i = 0; i < len / 2; i++)
  {
    if (s[i] != s[len - 1 - i])
      return false;
  }
  return true;
}

void rotateMatrix(vector<vector<int>> &v, int n)
{
  for (int i = 0; i < n / 2; i++)
  {
    for (int j = i; j < n - i - 1; j++)
    {
      int ptr = v[i][j];
      v[i][j] = v[n - 1 - j][i];
      v[n - 1 - j][i] = v[n - 1 - i][n - 1 - j];
      v[n - 1 - i][n - 1 - j] = v[j][n - 1 - i];
      v[j][n - 1 - i] = ptr;
    }
  }
}

vector<bool> is_prime(10001, 1);
vector<int> primes;

void seive()
{
  is_prime[0] = 0;
  is_prime[1] = 0;
  for (int i = 2; i < 10001; i++)
  {
    if (is_prime[i])
    {
      primes.push_back(i);
      for (int j = i + i; j < 10001; j += i)
      {
        is_prime[j] = 0;
      }
    }
  }
}

ll expo (ll x,ll n){
    ll result=1;
    while (n) {
        if (n & 1)
            result = result * x % MOD;
        n = n / 2;
        x = x * x % MOD;
    }
    return result;
}



int32_t main() {

  ll t; cin >> t;
  // seive();
  while (t--) {
   ll n; 
	    cin>>n; 
	    vector<ll> arr; 
	    for(ll i=0;i<n;i++){
	        ll x; 
	        cin>>x; 
	        arr.push_back(x); 
	    }
	    vector<ll> ans; 
	  
	   for(ll i=0;i<n;i++){
	       if(i==0){
	           cout<<(arr[i]&arr[i+1])<<" "; 
	           continue;
	       }else if(i==n-1){
	           cout<<(arr[i]&arr[i-1])<<" "; 
	       }else{
	           int ans = max(arr[i]&arr[i-1],arr[i]&arr[i+1]); 
	           cout<<ans<<" "; 
	       }
	   }
	    cout<<endl; 
    

          
  }
  return 0;
}

// 1b 4d

Maximum Damage CodeChef Solution in PYTH 3

# cook your dish here
def ans(arr):
    new_arr = []
    i = 0
    while i < len(arr):
        if i == 0:
            new_arr.append(arr[i] & arr[i + 1])
        elif i == len(arr) - 1:
            new_arr.append(arr[i] & arr[i - 1])
        else:
            new_arr.append(max(arr[i] & arr[i - 1], arr[i] & arr[i + 1]))
        i += 1
    return new_arr


test_cases = int(input())
while test_cases != 0:
    d = input()
    d2 = list(map(int, input().split()))
    print(*ans(d2))
    test_cases -= 1

Maximum Damage CodeChef Solution in C

#include <stdio.h>

int main(void) 
{
	int t;
	
	scanf("%d", &t);
	
	while(t--)
	{
	    int n;
	    
	    scanf("%d", &n);
	    
	    int a[n], b[n];
	    
	    for(int i=0; i<n; i++)
	    {
	        scanf("%d", &a[i]);
	    }
	    
	    b[0]=a[0]&a[1];
	    
	    for(int i=1; i<n-1; i++)
	    {
	        b[i]=a[i]&a[i-1];
	        
	        if(b[i] < (a[i]&a[i+1]))
	        {
	            b[i]=a[i]&a[i+1];
	        }
	    }
	    
	    b[n-1]=a[n-1]&a[n-2];
	    
	    for(int i=0; i<n; i++)
	    {
	        printf("%d ", b[i]);
	    }
	    
	    printf("\n");
	}
	return 0;
}

Maximum Damage CodeChef Solution in JAVA

/* package codechef; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
class Codechef
{
    
    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();
        }
 
        int nextInt() { return Integer.parseInt(next()); }
 
        long nextLong() { return Long.parseLong(next()); }
 
        double nextDouble()
        {
            return Double.parseDouble(next());
        }
 
        String nextLine()
        {
            String str = "";
            try {
                str = br.readLine();
            }
            catch (IOException e) {
                e.printStackTrace();
            }
            return str;
        }
    }
    static boolean prime[]= new boolean[10000001];
    public static void  sieve()
    {
        
        for(int i=0;i<=10000000;i++)
            prime[i] = true;
        prime[0] = prime[1] = false;
        for(int p = 2; p*p <=10000000; p++)
        {
            // If prime[p] is not changed, then it is a prime
            if(prime[p] == true)
            {
                // Update all multiples of p
                for(int i = p*p; i <= 10000000; i += p)
                    prime[i] = false;
            }
        }
        
    }
     static ArrayList<Integer> primeFactors(int n)
    {
        ArrayList<Integer> pflist=new ArrayList<>();
        int c = 2;
        while (n > 1) {
            if (n % c == 0) {
                pflist.add(c);
                n /= c;
            }
            else
                c++;
        }
        return pflist;
    }
    
	public static void main (String[] args) throws java.lang.Exception
	{
		// your code goes here
		FastReader sc = new FastReader();
		BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));
        
        int cases = sc.nextInt();
        //sieve();
        while(cases-->0)
        {
            int n = sc.nextInt();
            int[] ar=new int[n];
            for(int i=0;i<n;i++)
            {
                ar[i]=sc.nextInt();
            }
            out.write(((ar[0])&(ar[1]))+" ");
            for(int i=1;i<n-1;i++)
            {
                int leftVal=ar[i]&ar[i-1];
                int rightVal=ar[i]&ar[i+1];
                out.write(Math.max(leftVal,rightVal)+" ");
            }
            if(n>2)
            out.write(((ar[n-2])&(ar[n-1]))+" ");
            out.write("\n");
        }
        out.flush();
	}
	public static void reverse(int[] array)
	{
	    int n=array.length;
	    for(int i=0;i<n/2;i++)
	    {
	        int temp=array[i];
	        array[i]=array[n-i-1];
	        array[n-i-1]=temp;
	    }
	}
	public static String dectobin32(int x)
    {
        StringBuilder result = new StringBuilder();
 
        for (int i = 31; i >= 0 ; i--)
        {
            int mask = 1 << i;
            result.append((x & mask) != 0 ? 1 : 0);
        }
        //Integer.parseInt(result,2)
        return result.toString();
    }

}
class Pair implements Comparable<Pair> {
    int first,second;
    
    public Pair(int first,int second)
    {
        this.first =first;
        this.second=second;
    }
    public int compareTo(Pair b)
    {
        //first element in descending order
         if (this.first!=b.first)
            return (this.first>b.first)?-1:1;
        else 
            return this.second<b.second?-1:1;
            //second element in incresing order
    }
}

Maximum Damage CodeChef Solution in PYPY 3

def integer_list():
	return list(map(int, input().split()))

def string_list():
	return list(map(str, input().split()))

def hetro_list():
	return list(input().split())





import math	

from collections import Counter


def solve():




	res = print(lst[0]&lst[1], end=" ")

	for i in range(1, n-1):
		xafter = lst[i]&lst[i+1]
		xprev = lst[i]&lst[i-1]
		if xafter < xprev:
			print(xprev, end = " ")
		else:
			print(xafter, end = " ")
	print(lst[-2]&lst[-1])
	
		

t = int(input())

for _ in range(t):
	n = int(input())
	lst = integer_list()
	solve()

Maximum Damage CodeChef Solution in PYTH

t = int(raw_input())
for i in range(t):
	N = int(raw_input())
	st = raw_input().split()
	A = []
	for x in st:
		A.append(int(x))
	# endfor x
	n = A[0]&A[1]
	st = str(n) + ' '
	for k in range(1,N-1):
		n1 = A[k]&A[k+1]
		n2 = A[k]&A[k-1]
		n = max(n1,n2)
		st += str(n) + ' '
	# endfor k
	n = A[-1]&A[-2]
	st += str(n)
	print st
# endfor i

Maximum Damage CodeChef Solution in C#

using System;
using System.Linq;

public class Test
{
	public static void Main()
	{
		// your code goes here
		int T = Convert.ToInt32(Console.ReadLine());
		while( T > 0){
		    
		    int N = Convert.ToInt32(Console.ReadLine());
		    ulong[]arr = Console.ReadLine().Split(' ').Select(ulong.Parse).ToArray();
		    
		    
		    for(int i =0;i<N;i++){
		    ulong ans = arr[i];    
                if(i==0){
                    ans   = arr[0] & arr[1];
                }
                else if(i==N-1){
                    ans   = arr[N-1] & arr[N-2];
                }
		        else{
		            ans = Math.Max(arr[i] & arr[i+1], arr[i-1] & arr[i]);
		        }
		        
		        Console.Write(ans+ " ");
		    }
		    
		    Console.WriteLine();
		    
		    T--;
		}
	}
}

Maximum Damage CodeChef Solution in NODEJS

process.stdin.resume();
process.stdin.setEncoding('utf8');

let inputStdin = "";
let lineCounter = 0;
let _finalResult = "";
process.stdin.on('data', function (data) {
    inputStdin += data;
});
process.stdin.on('end', function () {
    inputStdin = inputStdin.toString().split('\n');
    start();
    printResult(); 
});
function printResult() {
    console.log(_finalResult);
}
function cout(x) {
    _finalResult += String(x);
}
function cinInt() {
    return Number(inputStdin[lineCounter++]);
}
function cinString() {
    return inputStdin[lineCounter++];
}
function cinArr() {
    return inputStdin[lineCounter++].split(' ').map(i => parseInt(i));
}


function start() {
    let t = cinInt();
    while(t--) {
        let n = cinInt();
        let a = cinArr();
        for(let i = 0; i < n; i++) {
            if(i !== 0 && i !== n - 1) {
                cout(Math.max(a[i] & a[i + 1], a[i] & a[i - 1]) + ' ');
            }
            else if(i === 0) {
                cout((a[i] & a[i + 1]) + ' ');
            }
            else {
                cout((a[i] & a[i - 1]) + ' ');
            }
        }
        cout('\n');
    }
}

Maximum Damage CodeChef Solution in GO

package main

import (
	"bufio"
	"bytes"
	"fmt"
	"os"
)

func main() {
	reader := bufio.NewReader(os.Stdin)

	tc := readNum(reader)

	var buf bytes.Buffer

	for tc > 0 {
		tc--
		n := readNum(reader)
		A := readNNums(reader, n)
		res := solve(A)
		for i := 0; i < n; i++ {
			buf.WriteString(fmt.Sprintf("%d ", res[i]))
		}
		buf.WriteByte('\n')
	}
	fmt.Print(buf.String())
}

func readInt(bytes []byte, from int, val *int) int {
	i := from
	sign := 1
	if bytes[i] == '-' {
		sign = -1
		i++
	}
	tmp := 0
	for i < len(bytes) && bytes[i] >= '0' && bytes[i] <= '9' {
		tmp = tmp*10 + int(bytes[i]-'0')
		i++
	}
	*val = tmp * sign
	return i
}

func readNum(reader *bufio.Reader) (a int) {
	bs, _ := reader.ReadBytes('\n')
	readInt(bs, 0, &a)
	return
}

func readTwoNums(reader *bufio.Reader) (a int, b int) {
	res := readNNums(reader, 2)
	a, b = res[0], res[1]
	return
}

func readThreeNums(reader *bufio.Reader) (a int, b int, c int) {
	res := readNNums(reader, 3)
	a, b, c = res[0], res[1], res[2]
	return
}

func readNNums(reader *bufio.Reader, n int) []int {
	res := make([]int, n)
	x := 0
	bs, _ := reader.ReadBytes('\n')
	for i := 0; i < n; i++ {
		for x < len(bs) && (bs[x] < '0' || bs[x] > '9') && bs[x] != '-' {
			x++
		}
		x = readInt(bs, x, &res[i])
	}
	return res
}

func readUint64(bytes []byte, from int, val *uint64) int {
	i := from

	var tmp uint64
	for i < len(bytes) && bytes[i] >= '0' && bytes[i] <= '9' {
		tmp = tmp*10 + uint64(bytes[i]-'0')
		i++
	}
	*val = tmp

	return i
}

const H = 30

func solve(A []int) []int {
	n := len(A)
	L := make([][]int, n)
	R := make([][]int, n)
	for i := 0; i < n; i++ {
		L[i] = make([]int, H)
		R[i] = make([]int, H)
	}

	for h := 0; h < H; h++ {
		for i := 0; i < n; i++ {
			if (A[i]>>uint(h))&1 == 1 {
				L[i][h] = 1
				if i > 0 {
					L[i][h] += L[i-1][h]
				}
			}
		}
		for i := n - 1; i >= 0; i-- {
			if (A[i]>>uint(h))&1 == 1 {
				R[i][h] = 1
				if i+1 < n {
					R[i][h] += R[i+1][h]
				}
			}
		}
	}

	res := make([]int, n)

	for i := 0; i < n; i++ {
		a, b := 0, n-1
		var cur int
		for h := H - 1; h >= 0; h-- {
			if (A[i]>>uint(h))&1 == 0 {
				// no contribution
				continue
			}
			l, r := i-L[i][h]+1, i+R[i][h]-1

			// if equal, means size = 1
			if max(a, l) < min(b, r) {
				cur |= 1 << uint(h)
				a = max(a, l)
				b = min(b, r)
			}
		}
		res[i] = cur
	}

	return res
}

func max(a, b int) int {
	if a >= b {
		return a
	}
	return b
}

func min(a, b int) int {
	if a <= b {
		return a
	}
	return b
}
Maximum Damage CodeChef Solution Review:

In our experience, we suggest you solve this Maximum Damage CodeChef Solution and gain some new skills from Professionals completely free and we assure you will be worth it.

If you are stuck anywhere between any coding problem, just visit Queslers to get the Maximum Damage CodeChef Solution.

Find on CodeChef

Conclusion:

I hope this Maximum Damage CodeChef Solution would be useful for you to learn something new from this problem. If it helped you then don’t forget to bookmark our site for more Coding Solutions.

This Problem is intended for audiences of all experiences who are interested in learning about Programming Language in a business context; there are no prerequisites.

Keep Learning!

More Coding Solutions >>

Cognitive Class Answer

CodeChef Solution

Microsoft Learn

Leave a Reply

Your email address will not be published. Required fields are marked *