#3366

Minimum Array Sum

Medium
ArrayDynamic ProgrammingDynamic ProgrammingState Space Exploration
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n * op1 * op2)
Space
O(1)
O(n * op1 * op2)
💡

Intuition

Time O(n * op1 * op2)Space O(n * op1 * op2)

The optimal approach uses dynamic programming to keep track of the minimum sum possible at each index with the remaining operations. This allows us to efficiently explore the state space without redundant calculations.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a 3D DP array where dp[i][j][l] represents the minimum sum possible using the first i elements with j operations of type 1 and l operations of type 2.
  2. 2Step 2: Iterate through each element and update the DP table based on whether we apply operation 1, operation 2, or neither.
  3. 3Step 3: Return the minimum value found in the last layer of the DP table.
solution.py13 lines
1def minArraySum(nums, k, op1, op2):
2    n = len(nums)
3    dp = [[[float('inf')] * (op2 + 1) for _ in range(op1 + 1)] for _ in range(n + 1)]
4    dp[0][0][0] = 0
5    for i in range(1, n + 1):
6        for j in range(op1 + 1):
7            for l in range(op2 + 1):
8                dp[i][j][l] = dp[i - 1][j][l] + nums[i - 1]
9                if j > 0:
10                    dp[i][j][l] = min(dp[i][j][l], dp[i - 1][j - 1][l] + (nums[i - 1] + 1) // 2)
11                if l > 0 and nums[i - 1] >= k:
12                    dp[i][j][l] = min(dp[i][j][l], dp[i - 1][j][l - 1] + nums[i - 1] - k)
13    return min(dp[n][j][l] for j in range(op1 + 1) for l in range(op2 + 1))

Complexity note: The complexity is O(n * op1 * op2) because we are iterating through each element and considering all combinations of operations left, leading to a manageable state space.

  • 1Using both operations strategically can lead to significant reductions in the sum.
  • 2Dynamic programming allows us to efficiently explore the state space without redundant calculations.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.