返回介绍

solution / 2200-2299 / 2270.Number of Ways to Split Array / README_EN

发布于 2024-06-17 01:03:08 字数 3806 浏览 0 评论 0 收藏 0

2270. Number of Ways to Split Array

中文文档

Description

You are given a 0-indexed integer array nums of length n.

nums contains a valid split at index i if the following are true:

  • The sum of the first i + 1 elements is greater than or equal to the sum of the last n - i - 1 elements.
  • There is at least one element to the right of i. That is, 0 <= i < n - 1.

Return _the number of valid splits in_ nums.

 

Example 1:

Input: nums = [10,4,-8,7]
Output: 2
Explanation: 
There are three ways of splitting nums into two non-empty parts:
- Split nums at index 0. Then, the first part is [10], and its sum is 10. The second part is [4,-8,7], and its sum is 3. Since 10 >= 3, i = 0 is a valid split.
- Split nums at index 1. Then, the first part is [10,4], and its sum is 14. The second part is [-8,7], and its sum is -1. Since 14 >= -1, i = 1 is a valid split.
- Split nums at index 2. Then, the first part is [10,4,-8], and its sum is 6. The second part is [7], and its sum is 7. Since 6 < 7, i = 2 is not a valid split.
Thus, the number of valid splits in nums is 2.

Example 2:

Input: nums = [2,3,1,0]
Output: 2
Explanation: 
There are two valid splits in nums:
- Split nums at index 1. Then, the first part is [2,3], and its sum is 5. The second part is [1,0], and its sum is 1. Since 5 >= 1, i = 1 is a valid split. 
- Split nums at index 2. Then, the first part is [2,3,1], and its sum is 6. The second part is [0], and its sum is 0. Since 6 >= 0, i = 2 is a valid split.

 

Constraints:

  • 2 <= nums.length <= 105
  • -105 <= nums[i] <= 105

Solutions

Solution 1

class Solution:
  def waysToSplitArray(self, nums: List[int]) -> int:
    s = sum(nums)
    ans = t = 0
    for v in nums[:-1]:
      t += v
      if t >= s - t:
        ans += 1
    return ans
class Solution {
  public int waysToSplitArray(int[] nums) {
    long s = 0;
    for (int v : nums) {
      s += v;
    }
    int ans = 0;
    long t = 0;
    for (int i = 0; i < nums.length - 1; ++i) {
      t += nums[i];
      if (t >= s - t) {
        ++ans;
      }
    }
    return ans;
  }
}
class Solution {
public:
  int waysToSplitArray(vector<int>& nums) {
    long long s = accumulate(nums.begin(), nums.end(), 0ll);
    long long t = 0;
    int ans = 0;
    for (int i = 0; i < nums.size() - 1; ++i) {
      t += nums[i];
      ans += t >= s - t;
    }
    return ans;
  }
};
func waysToSplitArray(nums []int) int {
  s := 0
  for _, v := range nums {
    s += v
  }
  ans, t := 0, 0
  for _, v := range nums[:len(nums)-1] {
    t += v
    if t >= s-t {
      ans++
    }
  }
  return ans
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文