diff --git a/Leetcode/MaWidthramp.java b/Leetcode/MaWidthramp.java new file mode 100644 index 0000000..39c5d1c --- /dev/null +++ b/Leetcode/MaWidthramp.java @@ -0,0 +1,42 @@ +/** + * + * 1402. Reducing Dishes +Solved +Hard +Topics +Companies +Hint +A chef has collected data on the satisfaction level of his n dishes. Chef can cook any dish in 1 unit of time. + +Like-time coefficient of a dish is defined as the time taken to cook that dish including previous dishes multiplied by its satisfaction level i.e. time[i] * satisfaction[i]. + +Return the maximum sum of like-time coefficient that the chef can obtain after preparing some amount of dishes. + +Dishes can be prepared in any order and the chef can discard some dishes to get this maximum value. + */ + + class Solution { + public int maxWidthRamp(int[] nums) { + int n = nums.length; + Stack stack = new Stack<>(); + + // Step 1: Build a decreasing stack of indices + for (int i = 0; i < n; ++i) { + if (stack.isEmpty() || nums[stack.peek()] > nums[i]) { + System.out.println(i); + stack.push(i); + } + } + + int maxWidth = 0; + + // Step 2: Traverse from the end and find maximum width ramp + for (int j = n - 1; j >= 0; --j) { + while (!stack.isEmpty() && nums[stack.peek()] <= nums[j]) { + maxWidth = Math.max(maxWidth, j - stack.pop()); + } + } + + return maxWidth; + } +} \ No newline at end of file