#3689

Maximum Total Subarray Value I

Medium
ArrayGreedyHash MapArray
LeetCode ↗

Approaches

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

Intuition

Time O(n)Space O(1)

The maximum total value can be achieved by selecting the entire array k times, as it provides the highest difference between max and min.

⚙️

Algorithm

3 steps
  1. 1Step 1: Calculate the maximum and minimum of the entire array.
  2. 2Step 2: Compute the value as max - min.
  3. 3Step 3: Multiply this value by k to get the total.
solution.py2 lines
1def maxTotalValue(nums, k):
2    return (max(nums) - min(nums)) * k

Complexity note: We only traverse the array twice to find max and min, leading to O(n) complexity.

  • 1Choosing the entire array maximizes the value.
  • 2The same subarray can be selected multiple times.

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