Skip to content

3010. Divide an Array Into Subarrays With Minimum Cost I 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
 public:
  int minimumCost(vector<int>& nums) {
    constexpr int kMax = 50;
    int min1 = kMax;
    int min2 = kMax;

    for (int i = 1; i < nums.size(); ++i)
      if (nums[i] < min1) {
        min2 = min1;
        min1 = nums[i];
      } else if (nums[i] < min2) {
        min2 = nums[i];
      }

    return nums[0] + min1 + min2;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
  public int minimumCost(int[] nums) {
    final int kMax = 50;
    int min1 = kMax;
    int min2 = kMax;

    for (int i = 1; i < nums.length; ++i)
      if (nums[i] < min1) {
        min2 = min1;
        min1 = nums[i];
      } else if (nums[i] < min2) {
        min2 = nums[i];
      }

    return nums[0] + min1 + min2;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution:
  def minimumCost(self, nums: list[int]) -> int:
    kMax = 50
    min1 = kMax
    min2 = kMax

    for i in range(1, len(nums)):
      if nums[i] < min1:
        min2 = min1
        min1 = nums[i]
      elif nums[i] < min2:
        min2 = nums[i]

    return nums[0] + min1 + min2