• Home
  • Top Posts
  • Code Solutions
  • How to
  • News
  • Trending
  • Anime
  • Health
  • Education
Wednesday, February 1, 2023
  • Login
Zeroplusfour
No Result
View All Result
  • Home
  • Top Posts
  • Code Solutions
  • How to
  • News
  • Trending
  • Anime
  • Health
  • Education
  • Home
  • Top Posts
  • Code Solutions
  • How to
  • News
  • Trending
  • Anime
  • Health
  • Education
No Result
View All Result
Zeroplusfour
No Result
View All Result
Home Code Solutions Hackerrank Algorithms

Dorsey Thief- HackerRank Solution

Dorsey Thief - HackerRank Solution Java , Python 3, Python 2 , C , C++, Best and Optimal Solutions , All you need.

admin by admin
August 23, 2022
Reading Time: 1 min read
0
15 Days to learn SQL Hard SQL(Advanced)-Solution

15 Days to learn SQL Hard SQL(Advanced)-Solution alt text

Spread the love

Table of Contents

  • Dorsey Thief – HackerRank Solution Java , Python 3, Python 2 , C , C++, Best and Optimal Solutions , All you need.
  • Solutions of Algorithms Data Structures Hard HackerRank:
    • Here are all the Solutions of Hard , Advanced , Expert Algorithms of Data Structure of Hacker Rank , Leave a comment for similar posts
  • C++ replace HackerRank Solution
  • Java rep HackerRank Solution
  • Python 3 rep HackerRank Solution
  • Python 2 rep HackerRank Solution
  • C rep HackerRank Solution
    • Warmup Implementation Strings Sorting Search Graph Theory Greedy Dynamic Programming Constructive Algorithms Bit Manipulation Recursion Game Theory NP Complete Debugging
    • Leave a comment below
      • Related posts:

Dorsey Thief – HackerRank Solution Java , Python 3, Python 2 , C , C++, Best and Optimal Solutions , All you need.

Solutions of Algorithms Data Structures Hard HackerRank:

Here are all the Solutions of Hard , Advanced , Expert Algorithms of Data Structure of Hacker Rank , Leave a comment for similar posts

C++ replace HackerRank Solution


Copy Code Copied Use a different Browser

#include <fstream>
#include <iostream>
#include <vector>
using namespace std;
int n, W;
#define LUNBUFFER 22000000 
int letti = -1;
char buff[LUNBUFFER];
int fast_read_int() {
    register  int let, n = 0;
    let = letti;
    do let++;
    while (buff[let] < '0');
    do {
        n = (n << 3) + (n << 1) + (buff[let++] - '0');
    } while (buff[let] >= '0');
    letti = let;
    return n;
}

vector<int>wt, val;
// A utility function that returns
// maximum of two integers
long long   max(long long  a, long long b) { return (a > b) ? a : b; }


// we can further improve the above Knapsack function's space
// complexity
long long  knapSack(int W, int n)//int wt[], int val[],
{
    int i, w;
    long long K[2][5000 + 1], r1, r2;
    // We know we are always using the the current row or
    // the previous row of the array/vector . Thereby we can
    // improve it further by using a 2D array but with only
    // 2 rows i%2 will be giving the index inside the bounds
    // of 2d array K

    for (i = 0; i <= n; i++) {
        //for (w = 0; w <= W; w++) {
        for (w = W; w >= 0; w--) {
            if (i == 0) {
                if (w == 0)
                    K[i % 2][w] = 0;
                else
                    K[i % 2][w] = -2;
            }
            else 
                if (wt[i - 1] <= w) {
                    r1 = K[(i - 1) % 2][w - wt[i - 1]];
                    r2 = K[(i - 1) % 2][w];
                    if (r1 < 0 && r2 < 0)
                        K[i % 2][w] = -2;
                    else
                        K[i % 2][w] = max(val[i - 1] + r1, r2);

                }
                else
                    K[i % 2][w] = K[(i - 1) % 2][w];
        }
    }
    return K[n % 2][W];
}

int main()
{
    //freopen("input.txt", "r", stdin);
    fread(buff, sizeof(char), LUNBUFFER, stdin);//_unlocked
    //freopen("output.txt", "w", stdout);
    n = fast_read_int();
    W = fast_read_int();
    //scanf("%d%d", &n, &W);
    //cin >> n >> W;
    wt.resize(n);
    val.resize(n);
    for (int i = 0; i < n; i++) {
        val[i] = fast_read_int();
        wt[i] = fast_read_int();
        //scanf("%d%d", &val[i], &wt[i]);
    }
    //cin >> val[i] >> wt[i];
    long long r = knapSack(W, n);
    if (r == -2)
        cout << "Got caught!";
    else
        cout << r;
    return 0;
}

Java rep HackerRank Solution


Copy Code Copied Use a different Browser

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

public class Solution {

	BufferedReader br;
	PrintWriter out;
	StringTokenizer st;
	boolean eof;

	void solve() throws IOException {
		int n = nextInt();
		int x = nextInt();

		long[] max = new long[x + 1];
		Arrays.fill(max, -1);
		max[0] = 0;

		long freeBonus = 0;

		List<Integer>[] byNeed = new List[x + 1];
		for (int i = 1; i <= x; i++) {
			byNeed[i] = new ArrayList<>(0);
		}

		for (int i = 0; i < n; i++) {
			int gain = nextInt();
			int need = nextInt();
			if (need == 0) {
				freeBonus += gain;
				continue;
			}
			if (need <= x) {
				byNeed[need].add(gain);
			}

		}

		for (int need = 1; need <= x; need++) {
			List<Integer> cur = byNeed[need];
			Collections.sort(cur);
			Collections.reverse(cur);
			for (int i = 0; (i + 1) * need <= x && i < cur.size(); i++) {
				int gain = cur.get(i);
				for (int j = x; j >= need; j--) {
					if (max[j - need] != -1) {
						max[j] = Math.max(max[j], max[j - need] + gain);
					}
				}
			}
		}

		if (max[x] == -1) {
			out.println("Got caught!");
		} else {
			out.println(max[x] + freeBonus);
		}
	}

	Solution() throws IOException {
		br = new BufferedReader(new InputStreamReader(System.in));
		out = new PrintWriter(System.out);
		solve();
		out.close();
	}

	public static void main(String[] args) throws IOException {
		new Solution();
	}

	String nextToken() {
		while (st == null || !st.hasMoreTokens()) {
			try {
				st = new StringTokenizer(br.readLine());
			} catch (Exception e) {
				eof = true;
				return null;
			}
		}
		return st.nextToken();
	}

	String nextString() {
		try {
			return br.readLine();
		} catch (IOException e) {
			eof = true;
			return null;
		}
	}

	int nextInt() throws IOException {
		return Integer.parseInt(nextToken());
	}

	long nextLong() throws IOException {
		return Long.parseLong(nextToken());
	}

	double nextDouble() throws IOException {
		return Double.parseDouble(nextToken());
	}
}

 



Python 3 rep HackerRank Solution


Copy Code Copied Use a different Browser

 



Python 2 rep HackerRank Solution


Copy Code Copied Use a different Browser

import heapq

def make_money(stolen, offers_dict):
    offers = [(weight, value) for (weight, values) in offers_dict.items() for value in values]
    offers.sort(key=lambda (weight, value): (weight, -value))
    chart = [None for _ in xrange(stolen+1)] # map weight to max value
    chart[0] = 0
    for (weight, value) in offers:
        no_more_expansions = True
        for chart_weight, chart_value in enumerate(chart[:]):
            if chart_value == None:
                continue

            new_weight = weight + chart_weight
            if new_weight > stolen:
                break

            no_more_expansions = False

            new_value = value + chart_value
            if chart[new_weight] == None:
                chart[new_weight] = new_value
            else:
                chart[new_weight] = max(chart[new_weight], new_value)

        if no_more_expansions:
            break

    if chart[stolen] != None:
        return chart[stolen]
    else:
        return "Got caught!"

def add_offer(offers, (value, weight), stolen):
    if weight <= stolen:
        if weight in offers:
            if len(offers[weight]) >= stolen / weight:
                heapq.heappushpop(offers[weight], value)
            else:
                heapq.heappush(offers[weight], value)
        else:
            offers[weight] = [value]

def main():
    passengers, stolen = map(int, raw_input().strip().split(" "))
    offers = {}
    for _ in xrange(passengers):
        offer = tuple(map(int, raw_input().strip().split(" ")))
        add_offer(offers, offer, stolen)

    print make_money(stolen, offers)

def test_speed():
    import random
    import cProfile

    passengers = 1000
    stolen = 1000
    random.seed(0)
    input_offers = ((random.randint(0, stolen), random.randint(0, stolen)) for _ in xrange(passengers))
    offers = {}
    for input_offer in input_offers:
        add_offer(offers, input_offer, stolen)

    print 'start profile'
    cProfile.runctx('make_money(stolen, offers)', {'stolen': stolen, 'offers': offers, 'make_money': make_money}, {})

def test_cases():
    stolen = 10
    input_offers = [(460, 4), (590, 6), (550, 5), (590, 5)]
    offers = {}
    for input_offer in input_offers:
        add_offer(offers, input_offer, stolen)

    result = make_money(stolen, offers)
    assert result == 1140, 'result: %s' % result

    stolen = 9
    input_offers = [(100, 5), (120, 10), (300, 2), (500, 3)]
    offers = {}
    for input_offer in input_offers:
        add_offer(offers, input_offer, stolen)

    result = make_money(stolen, offers)
    assert result == 'Got caught!', 'result: %s' % result
    
    stolen = 10
    input_offers = [(460, 5), (900, 5), (550, 5), (600, 5)]
    offers = {}
    for input_offer in input_offers:
        add_offer(offers, input_offer, stolen)

    result = make_money(stolen, offers)
    assert result == 1500, 'result: %s' % result

    print 'pass cases'

if __name__ == '__main__':
    main()
    #test_cases()
    #test_speed()



C rep HackerRank Solution


Copy Code Copied Use a different Browser


#include <stdio.h>
#include <stdlib.h>
void sort_a2(int*a,long long*b,int size);
void merge2(int*a,int*left_a,int*right_a,long long*b,long long*left_b,long long*right_b,int left_size, int right_size);

int main(){
  int N,X,i,j,k,*a,len,*index;
  long long *dp,temp,*v;
  scanf("%d%d",&N,&X);
  a=(int*)malloc(N*sizeof(int));
  v=(long long*)malloc(N*sizeof(long long));
  dp=(long long*)malloc((X+1)*sizeof(long long));
  index=(int*)malloc((X+1)*sizeof(int));
  for(i=1;i<=X;i++){
    dp[i]=-1;
    index[i]=-1;
  }
  dp[0]=0;
  for(i=0;i<N;i++)
    scanf("%lld%d",v+i,a+i);
  sort_a2(a,v,N);
  for(i=0;i<N && a[i]<=X;i++)
    if(i==0 || a[i]!=a[i-1])
      index[a[i]]=i;
  for(i=1;i<=X;i++){
    if(index[i]==-1)
      continue;
    len=X/a[index[i]]+index[i];
    for(k=index[i];k<len && k<N;k++){
      if(k!=index[i] && a[k]!=a[k-1])
        break;
      for(j=X;j>=a[k];j--){
        temp=(dp[j-a[k]]==-1)?-1:dp[j-a[k]]+v[k];
        if(temp>dp[j])
          dp[j]=temp;
      }
    }
  }
  if(dp[X]!=-1)
    printf("%lld",dp[X]);
  else
    printf("Got caught!");
  return 0;
}
void sort_a2(int*a,long long*b,int size){
  if (size < 2)
    return;
  int m = (size+1)/2,i;
  int *left_a,*right_a;
  long long *left_b,*right_b;
  left_a=(int*)malloc(m*sizeof(int));
  right_a=(int*)malloc((size-m)*sizeof(int));
  left_b=(long long*)malloc(m*sizeof(long long));
  right_b=(long long*)malloc((size-m)*sizeof(long long));
  for(i=0;i<m;i++){
    left_a[i]=a[i];
    left_b[i]=b[i];
  }
  for(i=0;i<size-m;i++){
    right_a[i]=a[i+m];
    right_b[i]=b[i+m];
  }
  sort_a2(left_a,left_b,m);
  sort_a2(right_a,right_b,size-m);
  merge2(a,left_a,right_a,b,left_b,right_b,m,size-m);
  free(left_a);
  free(right_a);
  free(left_b);
  free(right_b);
  return;
}
void merge2(int*a,int*left_a,int*right_a,long long*b,long long*left_b,long long*right_b,int left_size, int right_size){
  int i = 0, j = 0;
  while (i < left_size|| j < right_size) {
    if (i == left_size) {
      a[i+j] = right_a[j];
      b[i+j] = right_b[j];
      j++;
    } else if (j == right_size) {
      a[i+j] = left_a[i];
      b[i+j] = left_b[i];
      i++;
    } else if (left_a[i] < right_a[j]) {
      a[i+j] = left_a[i];
      b[i+j] = left_b[i];
      i++;
    }  else if (left_a[i] == right_a[j]) {
      if (left_b[i] <= right_b[j]) {
        a[i+j] = right_a[j];
        b[i+j] = right_b[j];
        j++;
      }
      else{
        a[i+j] = left_a[i];
        b[i+j] = left_b[i];
        i++;
      }
    }else {
      a[i+j] = right_a[j];
      b[i+j] = right_b[j];
      j++;
    }
  }
  return;
}

 

Warmup
Implementation
Strings
Sorting
Search
Graph Theory
Greedy
Dynamic Programming
Constructive Algorithms
Bit Manipulation
Recursion
Game Theory
NP Complete
Debugging

Leave a comment below

 

Related posts:

15 Days to learn SQL Hard SQL(Advanced)-SolutionAlmost Integer Rock Garden – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionDemanding Money- HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionAlex vs Fedor – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionAlien Languages – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionThe Longest Increasing Subsequence – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionSum vs XOR – HackerRank Solution
Tags: Cc++14full solutionGoHackerRank Solutionjavajava 15java 7java 8java8javascriptpypy 3Python 2python 3
ShareTweetPin
admin

admin

Related Posts

Leetcode All Problems Solutions
Code Solutions

Exclusive Time of Functions – LeetCode Solution

by admin
October 5, 2022
0
30

Exclusive Time of Functions - LeetCode Solution Java , Python 3, Python 2 , C , C++, Best and Optimal Solutions...

Read more
Leetcode All Problems Solutions

Smallest Range Covering Elements from K Lists – LeetCode Solution

October 5, 2022
32
Leetcode All Problems Solutions

Course Schedule III – LeetCode Solution

October 5, 2022
25
Leetcode All Problems Solutions

Maximum Product of Three Numbers – LeetCode Solution

September 11, 2022
52
Leetcode All Problems Solutions

Task Scheduler – LeetCode Solution

September 11, 2022
119
Leetcode All Problems Solutions

Valid Triangle Number – LeetCode Solution

September 11, 2022
28
Next Post
15 Days to learn SQL Hard SQL(Advanced)-Solution

Mining - HackerRank Solution

15 Days to learn SQL Hard SQL(Advanced)-Solution

Police Operation - HackerRank Solution

Leave a Reply Cancel reply

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

You may also like

15 Days to learn SQL Hard SQL(Advanced)-SolutionAlmost Integer Rock Garden – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionDemanding Money- HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionAlex vs Fedor – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionAlien Languages – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionThe Longest Increasing Subsequence – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionSum vs XOR – HackerRank Solution

Categories

  • Algorithms
  • Anime
  • Biography
  • Business
  • Code Solutions
  • Cosmos
  • Countdowns
  • Culture
  • Economy
  • Education
  • Entertainment
  • Finance
  • Games
  • Hackerrank
  • Health
  • How to
  • Investment
  • LeetCode
  • Lifestyle
  • LINUX SHELL
  • Manga
  • News
  • Opinion
  • Politics
  • Sports
  • SQL
  • Tech
  • Travel
  • Uncategorized
  • Updates
  • World
  • DMCA
  • Home
  • My account
  • Privacy Policy
  • Top Posts

Recent Blogs

Leetcode All Problems Solutions

Exclusive Time of Functions – LeetCode Solution

October 5, 2022
Leetcode All Problems Solutions

Smallest Range Covering Elements from K Lists – LeetCode Solution

October 5, 2022
Shark Tank
Business

What Happened To Doorbot After Shark Tank? Everything You need to know.

September 5, 2022
1
Leetcode All Problems Solutions
Code Solutions

H-Index – LeetCode Solution

September 6, 2022
45
Leetcode All Problems Solutions
Code Solutions

Relative Ranks – LeetCode Solution

September 10, 2022
28
15 Days to learn SQL Hard SQL(Advanced)-Solution
Code Solutions

Occupations Medium – SQL – HackerRank Solution

May 30, 2022
1

© 2022 ZeroPlusFour - Latest News & Blog.

No Result
View All Result
  • Home
  • Category
    • Business
    • Culture
    • Economy
    • Lifestyle
    • Health
    • Travel
    • Opinion
    • Politics
    • Tech
  • Landing Page
  • Support Forum
  • Contact Us

© 2022 ZeroPlusFour - Latest News & Blog.

Welcome Back!

Login to your account below

Forgotten Password?

Retrieve your password

Please enter your username or email address to reset your password.

Log In
We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “Accept All”, you consent to the use of ALL the cookies. However, you may visit "Cookie Settings" to provide a controlled consent.
Cookie SettingsAccept All
Manage consent

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary
Always Enabled
Necessary cookies are absolutely essential for the website to function properly. These cookies ensure basic functionalities and security features of the website, anonymously.
CookieDurationDescription
cookielawinfo-checkbox-analytics11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Analytics".
cookielawinfo-checkbox-functional11 monthsThe cookie is set by GDPR cookie consent to record the user consent for the cookies in the category "Functional".
cookielawinfo-checkbox-necessary11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookies is used to store the user consent for the cookies in the category "Necessary".
cookielawinfo-checkbox-others11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Other.
cookielawinfo-checkbox-performance11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Performance".
viewed_cookie_policy11 monthsThe cookie is set by the GDPR Cookie Consent plugin and is used to store whether or not user has consented to the use of cookies. It does not store any personal data.
Functional
Functional cookies help to perform certain functionalities like sharing the content of the website on social media platforms, collect feedbacks, and other third-party features.
Performance
Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.
Analytics
Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics the number of visitors, bounce rate, traffic source, etc.
Advertisement
Advertisement cookies are used to provide visitors with relevant ads and marketing campaigns. These cookies track visitors across websites and collect information to provide customized ads.
Others
Other uncategorized cookies are those that are being analyzed and have not been classified into a category as yet.
SAVE & ACCEPT
Are you sure want to unlock this post?
Unlock left : 0
Are you sure want to cancel subscription?