LeetCode 1058. Minimize Rounding Error to Meet Target

原题链接在这里:https://leetcode.com/problems/minimize-rounding-error-to-meet-target/description/

题目:

Given an array of prices [p1,p2...,pn] and a target, round each price pi to Roundi(pi) so that the rounded array [Round1(p1),Round2(p2)...,Roundn(pn)] sums to the given target. Each operation Roundi(pi) could be either Floor(pi) or Ceil(pi).

Return the string "-1" if the rounded array is impossible to sum to target. Otherwise, return the smallest rounding error, which is defined as Σ |Roundi(pi) - (pi)| for i from 1 to n, as a string with three places after the decimal.

Example 1:

Input: prices = ["0.700","2.800","4.900"], target = 8
Output: "1.000"
Explanation:
Use Floor, Ceil and Ceil operations to get (0.7 - 0) + (3 - 2.8) + (5 - 4.9) = 0.7 + 0.2 + 0.1 = 1.0 .

Example 2:

Input: prices = ["1.500","2.500","3.500"], target = 10
Output: "-1"
Explanation: It is impossible to meet the target.

Example 3:

Input: prices = ["1.500","2.500","3.500"], target = 9
Output: "1.500"

Constraints:

  • 1 <= prices.length <= 500
  • Each string prices[i] represents a real number in the range [0.0, 1000.0] and has exactly 3 decimal places.
  • 0 <= target <= 106

题解:

For each price, we either take the floor or the ceil. 
If target is out of [all floor, all ceil], then there is no way to sum up to target, return -1.

We use sum to mark all floor, if there is diff between price - floor(price), we add to maxHeap. It means later, we could use ceil.

If sum > target, that means target is smaller than all floor values, return -1.

If sum < target - maxHeap.size(), that means even we choose all the ceil + sum, still smaller than target, return -1.

Otherwise, we can sum to target.

target -= sum is the diff we want to conquer.

If this diff > 0, then it means we would like to take a ceil. That is why we want maxHeap to maintain the diff, that means mininum diff to the ceil.

Otherwise, we want the other way.

Time Complexity: O(nlogn). n = prices.length.

Space: O(n).

AC Java:

 1 class Solution {
 2     public String minimizeError(String[] prices, int target) {
 3         PriorityQueue<Double> maxHeap = new PriorityQueue<>(Collections.reverseOrder());
 4         int sum = 0;
 5         for(String price : prices){
 6             double p = Double.valueOf(price);
 7             sum += (int)p;
 8             double diff = p - (int)p;
 9             if(diff != 0){
10                 maxHeap.add(diff);
11             }
12         }
13 
14         if(sum > target || sum + maxHeap.size() < target){
15             return "-1";
16         }
17 
18         target -= sum;
19         double res = 0;
20         while(!maxHeap.isEmpty()){
21             double top = maxHeap.poll();
22             res += target > 0 ? (1 - top) : top;
23             target--;
24         }
25 
26         return String.format("%.3f", res);
27     }
28 }

 

posted @ 2024-08-03 04:41  Dylan_Java_NYC  阅读(8)  评论(0编辑  收藏  举报