|
| 1 | +package pp.arithmetic.leetcode; |
| 2 | + |
| 3 | +/** |
| 4 | + * Created by wangpeng on 2019-06-06. |
| 5 | + * 1052. 爱生气的书店老板 |
| 6 | + * <p> |
| 7 | + * 今天,书店老板有一家店打算试营业 customers.length 分钟。每分钟都有一些顾客(customers[i])会进入书店,所有这些顾客都会在那一分钟结束后离开。 |
| 8 | + * <p> |
| 9 | + * 在某些时候,书店老板会生气。 如果书店老板在第 i 分钟生气,那么 grumpy[i] = 1,否则 grumpy[i] = 0。 当书店老板生气时,那一分钟的顾客就会不满意,不生气则他们是满意的。 |
| 10 | + * <p> |
| 11 | + * 书店老板知道一个秘密技巧,能抑制自己的情绪,可以让自己连续 X 分钟不生气,但却只能使用一次。 |
| 12 | + * <p> |
| 13 | + * 请你返回这一天营业下来,最多有多少客户能够感到满意的数量。 |
| 14 | + * <p> |
| 15 | + * <p> |
| 16 | + * 示例: |
| 17 | + * <p> |
| 18 | + * 输入:customers = [1,0,1,2,1,1,7,5], grumpy = [0,1,0,1,0,1,0,1], X = 3 |
| 19 | + * 输出:16 |
| 20 | + * 解释: |
| 21 | + * 书店老板在最后 3 分钟保持冷静。 |
| 22 | + * 感到满意的最大客户数量 = 1 + 1 + 1 + 1 + 7 + 5 = 16. |
| 23 | + * <p> |
| 24 | + * <p> |
| 25 | + * 提示: |
| 26 | + * <p> |
| 27 | + * 1 <= X <= customers.length == grumpy.length <= 20000 |
| 28 | + * 0 <= customers[i] <= 1000 |
| 29 | + * 0 <= grumpy[i] <= 1 |
| 30 | + * |
| 31 | + * @see <a href="https://leetcode-cn.com/problems/grumpy-bookstore-owner/">grumpy-bookstore-owner</a> |
| 32 | + */ |
| 33 | +public class _1052_maxSatisfied { |
| 34 | + public static void main(String[] args) { |
| 35 | + _1052_maxSatisfied maxSatisfied = new _1052_maxSatisfied(); |
| 36 | + System.out.println(maxSatisfied.maxSatisfied(new int[]{1, 0, 1, 2, 1, 1, 7, 5}, new int[]{0, 1, 0, 1, 0, 1, 0, 1}, 3)); |
| 37 | + System.out.println(maxSatisfied.maxSatisfied(new int[]{1}, new int[]{0}, 1)); |
| 38 | + System.out.println(maxSatisfied.maxSatisfied(new int[]{4, 10, 10}, new int[]{1, 1, 0}, 2)); |
| 39 | + } |
| 40 | + |
| 41 | + /** |
| 42 | + * 解题思路(动态规划+窗口): |
| 43 | + * 1.定义两个数组dp和zoreDp |
| 44 | + * 2.dp保存窗口长度为X的满意度,防止重复计算 |
| 45 | + * 3.zoreDp保存不生气时候的满意总和数 |
| 46 | + * 4.第I位的最大值为窗口值+窗口前后的zoreDp之和 |
| 47 | + * |
| 48 | + * @param customers |
| 49 | + * @param grumpy |
| 50 | + * @param X |
| 51 | + * @return |
| 52 | + */ |
| 53 | + public int maxSatisfied(int[] customers, int[] grumpy, int X) { |
| 54 | + //存储第I位维持X位的满意数,防止重复计算 |
| 55 | + int[] dp = new int[customers.length + 1]; |
| 56 | + //存储不生气的满意总和数 |
| 57 | + int[] zoreDp = new int[customers.length + 1]; |
| 58 | + //初始化 |
| 59 | + int max = X > customers.length ? customers.length : X; |
| 60 | + int sum = 0; |
| 61 | + for (int i = 0; i < customers.length; i++) { |
| 62 | + if (i < X) { |
| 63 | + dp[i + 1] = sum += customers[i]; |
| 64 | + } |
| 65 | + zoreDp[i + 1] = (grumpy[i] == 0) ? customers[i] + zoreDp[i] : zoreDp[i]; |
| 66 | + } |
| 67 | + int retMax = dp[max] + zoreDp[customers.length] - zoreDp[max]; |
| 68 | + for (int i = X; i < customers.length; i++) { |
| 69 | + dp[i + 1] = dp[i] - customers[i - X] + customers[i]; |
| 70 | + int otherZore = zoreDp[customers.length] - zoreDp[i + 1] + zoreDp[i - X + 1]; |
| 71 | + retMax = Math.max(retMax, dp[i + 1] + otherZore); |
| 72 | + } |
| 73 | + |
| 74 | + return retMax; |
| 75 | + } |
| 76 | +} |
0 commit comments