CodingTour
ARTS #172

Algorithm

本周选择的算法题是:Maximum Score from Performing Multiplication Operations

规则

You are given two integer arrays nums and multipliers of size n and m respectively, where n >= m. The arrays are 1-indexed.

You begin with a score of 0. You want to perform exactly m operations. On the ith operation (1-indexed), you will:

  • Choose one integer x from either the start or the end of the array nums.
  • Add multipliers[i] * x to your score.
  • Remove x from the array nums.

Return the maximum score after performing m operations.

Example 1:

Input: nums = [1,2,3], multipliers = [3,2,1]
Output: 14
Explanation: An optimal solution is as follows:
- Choose from the end, [1,2,3], adding 3 * 3 = 9 to the score.
- Choose from the end, [1,2], adding 2 * 2 = 4 to the score.
- Choose from the end, [1], adding 1 * 1 = 1 to the score.
The total score is 9 + 4 + 1 = 14.

Example 2:

Input: nums = [-5,-3,-3,-2,7,1], multipliers = [-10,-5,3,4,6]
Output: 102
Explanation: An optimal solution is as follows:
- Choose from the start, [-5,-3,-3,-2,7,1], adding -5 * -10 = 50 to the score.
- Choose from the start, [-3,-3,-2,7,1], adding -3 * -5 = 15 to the score.
- Choose from the start, [-3,-2,7,1], adding -3 * 3 = -9 to the score.
- Choose from the end, [-2,7,1], adding 1 * 4 = 4 to the score.
- Choose from the end, [-2,7], adding 7 * 6 = 42 to the score. 
The total score is 50 + 15 - 9 + 4 + 42 = 102.

Constraints:

  • n == nums.length
  • m == multipliers.length
  • 1 <= m <= 103
  • m <= n <= 105``
  • -1000 <= nums[i], multipliers[i] <= 1000

Solution

impl Solution {
    pub fn maximum_score(nums: Vec<i32>, multipliers: Vec<i32>) -> i32 {
        let (n, m) = (nums.len(), multipliers.len());
        let mut dp = vec![vec![0; m + 1]; m + 1];

        for op in (0..m).rev() {
            for left in (0..=op).rev() {
                dp[op][left] = (multipliers[op] * nums[left] + dp[op+1][left+1]).max(
                    multipliers[op] * nums[n-1-(op-left)] + dp[op+1][left]
                );
            }
        }

        dp[0][0]
    }
}

Review

Programmer, Developer and Engineer: What’s the difference?

挺有趣的一篇文章,简单来说就是:

  • 程序员完成工作
  • 开发者做好工作
  • 工程师解决问题

基本上认同吧~

Tip

号称世界上最大的 API 平台 RapidAPI

Share

对自动化开始时机的看法。

先引用一句 Airbnb 的创始人 Brian Chesky 说的 “秘密”:对每件事都亲力亲为直到做不下去,然后实现自动化。

这句话很形象的概括了做自动化要经历的几个阶段:

  1. 了解如何做
  2. 交给别人做
  3. 实现自动化

但在实际工作中还是很容易进入误区,常见误区如下:

  • 过早考虑自动化 - 在创造和使用工具上,工程师的热情是高涨的,但如果没有想清楚当下处于什么阶段,这一点恰恰会成为劣势:太早,前期投入过多,没有聚焦解决关键问题,很可能最后发现是无用功;但也不能太晚决策,这会失去扩张性
  • 排斥用 “笨方法” - 一个方法能不能解决问题是衡量最终价值的判断标准,随手能用的东西,比很厉害但不顺手的好 100 倍
  • 反馈周期太长 - 如果因为看不懂重心在哪里,往往也害怕因为自己的舍弃而丢失掉重要的东西,事物并不只有 0 和 1 两个极端,如果看清了 1,但只做 0.3,有了舍弃,才能不断地给团队带来积极反馈

要避免进入误区很容易,只需要找到关键节点,定义关键任务。当在组织和团队中进行多人协作时,清晰度非常重要。

我在判断合适时机是否已来时,会自问一个问题:有没有什么方法可以推迟引入自动化?很明显,一个巧妙的方法可以推迟引入自动化的时机,而且有时候这种方式能够产生出创新手段。

回到我们最初说的那三个阶段,其实它们都有各自的意图:

  1. 了解如何做 - 掌握细节
  2. 交给别人做 - 观察可复制性
  3. 实现自动化 - 固化流程、重复化

最后总结一下:手里有啥就用啥,先操起家伙做起来,不要怕弄脏双手,快速获得正向反馈后,才有机会发展下去。