From 1d07d142d07e8dca5fac0457059ca159dc9f295c Mon Sep 17 00:00:00 2001 From: Alexander Pantyukhin Date: Sat, 17 Dec 2022 01:42:57 +0400 Subject: [PATCH] feat: add Number of Ways to Split Array LeetCode (#1165) Co-authored-by: David Leal --- leetcode/DIRECTORY.md | 1 + leetcode/src/2270.c | 21 +++++++++++++++++++++ 2 files changed, 22 insertions(+) create mode 100644 leetcode/src/2270.c diff --git a/leetcode/DIRECTORY.md b/leetcode/DIRECTORY.md index 78bddea3..c0cf88f9 100644 --- a/leetcode/DIRECTORY.md +++ b/leetcode/DIRECTORY.md @@ -109,4 +109,5 @@ | 1752 | [Check if Array Is Sorted and Rotated](https://leetcode.com/problems/check-if-array-is-sorted-and-rotated/) | [C](./src/1752.c) | Easy | | 2024 | [Maximize the Confusion of an Exam](https://leetcode.com/problems/maximize-the-confusion-of-an-exam/) | [C](./src/2024.c) | Medium | | 2130 | [Maximum Twin Sum of a Linked List](https://leetcode.com/problems/maximum-twin-sum-of-a-linked-list/) | [C](./src/2130.c) | Medium | +| 2270 | [Number of Ways to Split Array](https://leetcode.com/problems/number-of-ways-to-split-array/) | [C](./src/2270.c) | Medium | | 2304 | [Minimum Path Cost in a Grid](https://leetcode.com/problems/minimum-path-cost-in-a-grid/) | [C](./src/2304.c) | Medium | diff --git a/leetcode/src/2270.c b/leetcode/src/2270.c new file mode 100644 index 00000000..b797f567 --- /dev/null +++ b/leetcode/src/2270.c @@ -0,0 +1,21 @@ +// Prefix sum. +// Collect sum fromleft part and compare it with left sum. +// Runtime: O(n) +// Space: O(1) +int waysToSplitArray(int* nums, int numsSize){ + long sumNums = 0; + for (int i = 0; i < numsSize; i++){ + sumNums += nums[i]; + } + + long prefixSum = 0; + int result = 0; + for (int i = 0; i < numsSize - 1; i++){ + prefixSum += nums[i]; + if (prefixSum >= sumNums - prefixSum){ + result += 1; + } + } + + return result; +}