AfterAcademy Tech
•
13 Jan 2020

Difficulty: Medium
Asked in: Amazon
We are given N items with their corresponding weights and values, we have a knapsack weighing W. We have to choose among these N items to put into the knapsack such that the value of the knapsack is maximum. For example:
Input: items[] = [ [60, 10], [100, 20], [120, 30] ]
Knapsack Capacity(capacity) = 50
Output: Maximum possible value = 240
Explanation: By taking full items of 10 kg, 20 kg and 2/3rd of last item of 30 kg. Total value = 60 + 100 + 120*2/3 = 240
Possible follow-up questions to ask the interviewer: →
Solution idea
Here the problem is to find the maximum profit possible from the items[] and we are also allowed to take fractions of the items. This is an optimization problem which can be solved by applying greedy algorithm startegy. In this algorithm, we go on choosing the locally optimal choice (or the greedy choice) with a consideration that it will lead to globally optimal solution.
Lets think about the solution insights. Which item will you pick first (Greedy choice)? One startegy is to maximize the profit with every choice and pick the item with the largest ratio of value/weight. This will assure us that we will reach to the globally optimal profit. (Think!)
Solution steps
Pseudo-code
double fractionalKnapsack(int K, item A[], int N)
{
//Sort the items on the basis of increasing ratio of V/W
sort(A, A+N)
double totalValue = 0.0
int currUsedWeight = 0
for(int i = 0 to N-1)
{
if(A[i].weight < K)
{
totalValue = totalValue + A[i].value
currUsedWeight = currUsedWeight + A[i].weight
}
else
{
int availableSpace = K - currUsedSpace
//Taking the Fraction
totalValue = totalValue + A[i].value*(availableSpace/A[i].weight)
break
}
}
}
Complexity Analysis
Time Complexity: Time complexity of the sorting + Time complexity of the loop to maximize profit = O(NlogN) + O(N) = O(NlogN)
Space Complexity: O(1)
Critical ideas to think!
Happy Coding! Enjoy Algorithms!!
AfterAcademy Tech
This is an interview problem asked in companies like Amazon, Microsoft, Yahoo and Adobe. The problem is to design a stack that will support push(), pop(), top() and getMin() operation in constant time. We will be discussing two different ways to approach this problem.

AfterAcademy Tech
In this blog, we will learn about the classic reader-writer problem in Operating System. We will also see how to remove this problem in Operating System.

AfterAcademy Tech
In this blog, we will learn about the Producer-Consumer problem in Operating System and we will also learn how to solve this problem. It is used in multi-process synchronization.

AfterAcademy Tech
This is a mathematical problem asked in interviews of Google like companies. For solving such problems you need to have some math skills and also some idea of algorithms like Euclid's GCD algorithm.
