Chef and Integers CodeChef Solution

Problem -Chef and Integers 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.

Chef and Integers CodeChef Solution in C++14

#include<bits/stdc++.h>

#define ll long long

using namespace std;

ll solve(vector<ll> v,ll x,int n)
{
    if(x==0)
    return 0;
    
     ll mi=*min_element(v.begin(),v.end());
     
     if(mi>=0)
     return 0;
    
    if(x==1)
    {
        return abs(mi);
    }
    
        
    vector<ll> b;
    
    for(int i=0;i<n;i++)
    {
        if(v[i]<0)
        b.push_back(v[i]);
    }
    
    
    if(x>=b.size())
    {
        ll sum=0;
        for(int i=0;i<b.size();i++)
        {
            sum+=abs(b[i]);
        }
        return sum;
    }
    
    sort(v.begin(),v.end());
	ll ans;
	
	    ll sum=0;
	    for(int i=0;i<(x-1);i++)
	    {
	        sum+=(v[x-1]-v[i]);
	    }
	 ans=(-v[x-1])*x + sum;

    return ans;
    
}

int main() {
    
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    
    int n;
    cin>>n;
    
    vector<ll> v(n);
    
    for(int i=0;i<n;i++)
    cin>>v[i];
    
    ll x;
    cin>>x;
    
   cout<<solve(v,x,n)<<endl;


	return 0;
}

Chef and Integers CodeChef Solution in PYTH 3

# cook your dish here
import bisect


def solve(n, arr, x):
    if x == 0:
        return 0
    num_negative = 0
    negative_sorted = []
    sum_negative = 0
    for i in range(len(arr)):
        if arr[i] < 0:
            sum_negative += arr[i]
            bisect.insort(negative_sorted, arr[i])
    if x >= len(negative_sorted):
        return (-1) * sum_negative
    z = len(negative_sorted) - x
    sum_negative -= negative_sorted[z]*x
    sum_negative += negative_sorted[z]*x
    for i in range(0, z):
        sum_negative -= negative_sorted[-i-1]
    return (-1) * sum_negative


N = input()
Arr = list(map(int, input().split()))
X = int(input())
print(solve(N, Arr, X))

Chef and Integers CodeChef Solution in C

#include<stdio.h>
#include<math.h>
long int cmp(const void *a,const void *b)
{
    return(*(long int*)a-*(long int*)b);
}
int main()
{
    int n;
    scanf("%d",&n);
    long int a[n],b[n];
    long long int x;
    int u=0;
    long long int s=0;
    for(int i=0;i<n;i++)
    {
        scanf("%ld",&a[i]);
        if(a[i]<0)
        {s+=fabs(a[i]);
        b[u++]=a[i];
        }
    }
    scanf("%lld",&x);
    if(x==0)
    {printf("0\n");return 0;
    }
    qsort(b,u,sizeof(long int),cmp);
    if(x>=s)
    {
        printf("%lld\n",s);return 0;
    }
    long long int minimum=s;
    long long int r;
    long long int v=0;
    for(int i=0;i<u-1;i++)
    {
       r=(fabs(b[i]))*x+v;
       if(r<minimum)
        minimum=r;
       v+=(fabs(b[i]-b[i+1]))*(i+1);
    }
    printf("%lld\n",minimum);
    return 0;
}

Chef and Integers CodeChef Solution in JAVA

import java.util.*;
import java.io.*;
class Codechef{
    static class FastReader{
        BufferedReader br;
        StringTokenizer st;
        public FastReader(){
            br=new BufferedReader(new InputStreamReader(System.in));
        }
        String next(){
            while(st==null || !st.hasMoreTokens()){
                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().trim();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return str;
        }
    }
    static class FastWriter {
		private final BufferedWriter bw;

		public FastWriter() {
			this.bw = new BufferedWriter(new OutputStreamWriter(System.out));
		}

		public void print(Object object) throws IOException {
			bw.append("" + object);
		}

		public void println(Object object) throws IOException {
			print(object);
			bw.append("\n");
		}

		public void close() throws IOException {
			bw.close();
		}
	}
	static long sumOfNegative(int A[],int start,int end){
	    long sum=0;
	    for(int i=start;i<=end;i++){
	        if(A[i]<0)
	           sum+=A[i];
	    }
	    return sum;
	}
	public static void main (String[] args)throws Exception{
		FastReader in=new FastReader();
        FastWriter out = new FastWriter();
		    int N=in.nextInt();
		    int A[]=new int[N];
		    for(int i=0;i<N;i++)
    		    A[i]=in.nextInt();
		    int X=in.nextInt();
		    Arrays.sort(A);
		    long cost=0;
		    if(X<=1){
		        if(A[0]<0)
		            cost=(A[0]*(-1))*X;
		    }
		    else if(X>N)
		       cost=sumOfNegative(A,0,N-1)*(-1);
		    else{
		        long sum=sumOfNegative(A,0,X-1);
		        if(A[X-1]<0){
		            sum+=X*(A[X-1]*(-1));
		            cost=X*(A[X-1]*(-1));
		        }
		        if(sum<0)
		           cost+=sum*(-1);
		    }
		    out.println(cost);
		out.close();
	}
}

Chef and Integers 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
import sys
from collections import Counter

def main():
	new_lst = [ele for ele in lst if ele < 0]

	new_lst.sort()

	cost = 0
	k = len(new_lst)
	added = 0
	ans = 0
	while new_lst:
		indv_cost = k
		comb_cost = x
		added += 1
		ans += min(indv_cost, comb_cost)
		while new_lst:
			if new_lst[-1] + added >= 0:
				new_lst.pop()
				k = k -1
			else:
				break
	print(ans)
	


	
	

# t = int(input())


for _ in range(1):
	n = int(input())
	lst = integer_list()
	x = int(input())
	main()

Chef and Integers CodeChef Solution in PYTH

N = int(raw_input())
st = raw_input().split()
A = []
for x in st:
	n = int(x)
	if n < 0:
		A.append(n)
	# endif
# endfor x
A.sort()
sz = len(A)
X = int(raw_input())
sz = min(sz,X)
tot = 0
for k in range(sz):
	tot += A[k]
# endfor k
tot = -tot
print tot

Chef and Integers CodeChef Solution in C#

using System;
using System.Linq;

static class Program {
	public static void Main() {
		int N = int.Parse(Console.ReadLine());
		int[] A = Console.ReadLine().Split(null).Select(a => -int.Parse(a))
			.Where(a => a > 0).ToArray();
		Array.Sort(A);
		long X = long.Parse(Console.ReadLine());
		long minimalCost;
		if (X == 0) {
			minimalCost = 0;
		}
		else if (X <= A.Length) {
			minimalCost = A[A.Length - X] * X;
			for (int i = A.Length - (int)X + 1; i < A.Length; ++i) {
				minimalCost += A[i] - A[A.Length - X];
			}
		}
		else {
			minimalCost = 0;
			for (int i = 0; i < A.Length; ++i) {
				minimalCost += A[i];
			}
		}
		Console.WriteLine(minimalCost);
	}
}

Chef and Integers CodeChef Solution in NODEJS

var input = '';

function cacheInput(data) {
	input += data;
}

function callMain() {
	input = input.split(/\s+/).map(Number);
	main();
}

var readNumber = function() {
	var i = -1;
	return function() {
		return input[++i];
	};
}();

function main() {
	var N = readNumber();
	var A = [];
	var sumA = 0;
	for (var i = 0; i < N; ++i) {
		var number = readNumber();
		if (number < 0) {
			A.push(-number);
			sumA += -number;
		}
	}
	A.sort(function(a, b) { return a - b; });
	var X = readNumber();
	var minimalCost = 0;
	if (X == 0) {
	}
	else if (X <= A.length) {
		minimalCost = A[A.length - X] * X;
		for (var i = A.length - X + 1; i < A.length; ++i) {
			minimalCost += A[i] - A[A.length - X];
		}
	}
	else {
		minimalCost = sumA;
	}
	process.stdout.write(minimalCost + '\n');
	process.exit();
}

process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', cacheInput).on('end', callMain);

Chef and Integers CodeChef Solution in GO

package main

import "bufio"
import "fmt"
import "os"
import "math"
import "strconv"
import "strings"
import "sort"

func Checkerr(err error) {
	if err != nil {
		fmt.Println("problem", err)
		os.Exit(2)
	}
}

func NextLine(reader *bufio.Reader) string {
        line, err := reader.ReadString('\n')
        Checkerr(err)
	return strings.TrimSpace(line)
}

func ParseInt(s string) int {
	n, err := strconv.Atoi(s)
	Checkerr(err)
	return n
}

func AssertEquals(a, b int64, msg string) {
	if a != b {
		fmt.Println("AssertEquals Failed:", a, "!=", b, ",", msg)
		os.Exit(2)
	}
}

func Solve(ints []int, x int) int64 {
	new_ints := make([]int, 0)
	for i:=0; i<len(ints); i++ {
		if ints[i] < 0 {
			new_ints = append(new_ints, ints[i])
		}
	}
	ints = new_ints

	var cost int64 = 0

	sort.Ints(ints)

	if x > 0 && x <= len(ints) {
		cost = -1 * int64(x) * int64(ints[x-1])
		for i:=0; i<int(math.Min(float64(len(ints)), float64(x-1))); i++ {
			cost += int64(ints[x-1]) - int64(ints[i])
		}
	} else {
		for i:=0; i<int(math.Min(float64(len(ints)), float64(x-1))); i++ {
			cost -= int64(ints[i])
		}
	}

//	if x < len(ints) && ints[x] < 0 {
//		max := -1 * ints[x]
//		ints = ints[:x]
//		for i, _ := range ints {
//			ints[i] += max
//		}
//		cost += int64(max * x)
//	}
//
//	for _, v := range ints {
//		if v < 0 {
//			cost -= int64(v)
//		}
//	}

	return cost
}

func Test() {
	AssertEquals(Solve([]int{0}, 3), 0, "")
	AssertEquals(Solve([]int{-1}, 0), 0, "")
	AssertEquals(Solve([]int{-1}, 3), 1, "")
	AssertEquals(Solve([]int{-4, -3, 5}, 1), 4, "")
	AssertEquals(Solve([]int{-1, -2, 1}, 3), 3, "3-3")
	AssertEquals(Solve([]int{-2, -3}, 1), 3, "2-1")
	AssertEquals(Solve([]int{-2, -3, 1, 2}, 1), 3, "4-1")
	AssertEquals(Solve([]int{-2, -3}, 2), 5, "2-2")
	AssertEquals(Solve([]int{-2, -3}, 0), 0, "")
	AssertEquals(Solve([]int{-2, -3}, 3), 5, "2-3")
	AssertEquals(Solve([]int{-1,-2,-3}, 3), 6, "3-3")
	AssertEquals(Solve([]int{-1,-2,-3}, 2), 5, "3-2")
	AssertEquals(Solve([]int{-1,-2,-3}, 4), 6, "3-4")
	AssertEquals(Solve([]int{-1,-2,-3,-4}, 2), 7, "4-2")
}

func Ingest() {
        reader := bufio.NewReader(os.Stdin)
	n := ParseInt(NextLine(reader))
	ints := make([]int, n)
	for i, s := range strings.Split(NextLine(reader), " ") {
		v := ParseInt(s)
		ints[i] = v
	}
	x := int(ParseInt(NextLine(reader)))
	fmt.Println(Solve(ints, x))
}

func main() {
	Ingest()
	//Test()
}
Chef and Integers CodeChef Solution Review:

In our experience, we suggest you solve this Chef and Integers 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 Chef and Integers CodeChef Solution.

Find on CodeChef

Conclusion:

I hope this Chef and Integers 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 *