diff options
author | Jack Sangdahl <[email protected]> | 2025-01-03 13:04:42 +0100 |
---|---|---|
committer | Jack Sangdahl <[email protected]> | 2025-01-03 13:04:42 +0100 |
commit | 58aad8b80409fc95ffb1b01e0cc70c1a64e08bc2 (patch) | |
tree | 07aae731bda8ad3c108846ce784a012161b0072d | |
parent | 0d437ad50acc4103a9316281c5a020e6773cf5d5 (diff) | |
download | leetcode-58aad8b80409fc95ffb1b01e0cc70c1a64e08bc2.tar.gz leetcode-58aad8b80409fc95ffb1b01e0cc70c1a64e08bc2.zip |
2270. number of ways to split array
-rw-r--r-- | num_ways_split_arr.c | 30 | ||||
-rw-r--r-- | num_ways_split_arr.py | 33 |
2 files changed, 63 insertions, 0 deletions
diff --git a/num_ways_split_arr.c b/num_ways_split_arr.c new file mode 100644 index 0000000..a7d603a --- /dev/null +++ b/num_ways_split_arr.c @@ -0,0 +1,30 @@ +// 2270. Number of Ways to Split Array +#include "leetcode.h" + +/* + * you are given a 0-indexed integer array 'nums' of lenght '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, and there is at least one element to the right of 'i'. return the + * number of valid splits in 'nums'. + */ + +int waysToSplitArray(int *nums, int numsSize) { + long long end = 0, start = 0; + for (int i = 0; i < numsSize; i++) + end += nums[i]; + int ans = 0; + for (int i = 0; i < numsSize - 1; i++) { + start += nums[i]; + end -= nums[i]; + if (start >= end) + ans++; + } + return ans; +} + +int main() { + int n1[] = {10, 4, -8, 7}, n2[] = {2, 3, 1, 0}; + printf("%d\n", waysToSplitArray(n1, ARRAY_SIZE(n1))); // expect: 2 + printf("%d\n", waysToSplitArray(n2, ARRAY_SIZE(n2))); // expect: 2 +} diff --git a/num_ways_split_arr.py b/num_ways_split_arr.py new file mode 100644 index 0000000..28cf758 --- /dev/null +++ b/num_ways_split_arr.py @@ -0,0 +1,33 @@ +# 2270. Number of Ways to Split Array + +""" +you are given a 0-indexed integer array 'nums' of lenght '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, and there is at least one element to the right of 'i'. return the +number of valid splits in 'nums'. +""" + + +class Solution(object): + def waysToSplitArray(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + end, start = 0, 0 + for i in range(0, len(nums)): + end += nums[i] + ans = 0 + for i in range(0, len(nums) - 1): + start += nums[i] + end -= nums[i] + if start >= end: + ans += 1 + return ans + + +if __name__ == "__main__": + obj = Solution() + print(obj.waysToSplitArray(nums=[10, 4, -8, 7])) + print(obj.waysToSplitArray(nums=[2, 3, 1, 0])) |