Skip to content

← leetcode

Number of Ways to Split Array

· Medium

LeetCode problem 2270

(I think they misclassified this problem)

My algorithm just calculates the sum of the integer array nums, and then iterates through the integer array, at each step calculating the cumulative sum and subtracting from the total sum to determine whether or not the split is valid or not.

code

class Solution {
public:
    int waysToSplitArray(vector<int>& nums) {
        long long sum = 0;
        for (int i = 0; i < nums.size(); ++i) {
            sum += nums[i];
        }

        int ans = 0;
        long long temp = 0;
        for (int i = 0; i < nums.size()-1; ++i) {
            temp += nums[i];

            if (temp >= sum-temp) ++ans;
        }
        return ans;
    }
};

complexity

  • Time: O(n)
  • Space: O(1)