Write a Java program that finds the heaviest stack of boxes that you can create
ID: 3870980 • Letter: W
Question
Write a Java program that finds the heaviest stack of boxes that you can create out of a set of boxes given as input. Input: The input to the program is a file containing a set of boxes. Each line of the input file represents one box with 4 numbers, in the following format: Name Height Width Depth Weight. Depth always 2 width Rules for Box Stacking: A box X may be stacked on top of another box Y if and only if both of the following conditions hold: X has a footprint no bigger than Y in either width or depth (so if you stack X on Y, there is no overhang) · . Box X weiahs no more than box Y. Algorithm: You must do a dynamic programming algorithm for this problem.Explanation / Answer
public class RectArea
static int getMaxArea(int hist[], int n)
{
Stack<Integer> s = new Stack<>();
int max_area = 0;
int tp;
int area_with_top;
int i = 0;
while (i < n)
{
if (s.empty() || hist[s.peek()] <= hist[i])
s.push(i++);
else
{
tp = s.peek();
s.pop();
area_with_top = hist[tp] * (s.empty() ? i : i - s.peek() - 1);
if (max_area < area_with_top)
max_area = area_with_top;
}
}
while (s.empty() == false)
{
tp = s.peek();
s.pop();
area_with_top = hist[tp] * (s.empty() ? i : i - s.peek() - 1);
if (max_area < area_with_top)
max_area = area_with_top;
}
return max_area;
}
public static void main(String[] args)
{
int hist[] = { 6, 2, 5, 4, 5, 1, 6 };
System.out.println("Maximum area is " + getMaxArea(hist, hist.length));
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.