diff options
author | Jack Sangdahl <[email protected]> | 2024-10-05 18:16:45 -0600 |
---|---|---|
committer | Jack Sangdahl <[email protected]> | 2024-10-05 18:17:01 -0600 |
commit | b4d0b099e1641df61f69df63c2204d42c11c1ba7 (patch) | |
tree | c6cfe4693584bc0e1266247c965a317abe2de288 /max_abs_sum_any_subarr.c | |
parent | 6b43fe61b0a788d116e4cb53aabc1be621f97263 (diff) | |
download | leetcode-b4d0b099e1641df61f69df63c2204d42c11c1ba7.tar.gz leetcode-b4d0b099e1641df61f69df63c2204d42c11c1ba7.zip |
1749. maximum absolute sum of any subarray
Diffstat (limited to 'max_abs_sum_any_subarr.c')
-rw-r--r-- | max_abs_sum_any_subarr.c | 34 |
1 files changed, 34 insertions, 0 deletions
diff --git a/max_abs_sum_any_subarr.c b/max_abs_sum_any_subarr.c new file mode 100644 index 0000000..8ddd1eb --- /dev/null +++ b/max_abs_sum_any_subarr.c @@ -0,0 +1,34 @@ +// 1749. Maximum Absolute Sum of Any Subarray +#include "leetcode.h" + +/* + * you are given an integer array 'nums'. the absolute sum of a subarray '[nums, + * nums[i + 1], ..., nums[r]]' is 'abs(nums, nums[i], ..., nums[r])'. return the + * maximum absolute sum of any (possibly empty) subarray of 'nums'. note that + * 'abs(x)' is defined as follows: if 'x' is negative integer, then 'abs(x) = + * -x'. if 'x' is a non negative integer, then 'abs(x) = x' + */ + +int maxAbsoluteSum(int *nums, int numsSize) { + int max_sum = INT_MIN, min_sum = INT_MAX, curr_sum = 0; + for (int i = 0; i < numsSize; i++) { + curr_sum += nums[i]; + max_sum = max_sum > curr_sum ? max_sum : curr_sum; + if (curr_sum < 0) + curr_sum = 0; + } + curr_sum = 0; + for (int i = 0; i < numsSize; i++) { + curr_sum += nums[i]; + min_sum = min_sum < curr_sum ? min_sum : curr_sum; + if (curr_sum > 0) + curr_sum = 0; + } + return abs(max_sum) > abs(min_sum) ? abs(max_sum) : abs(min_sum); +} + +int main() { + int n1[] = {1, -3, 2, 3, -4}, n2[] = {2, -5, 1, -4, 3, -2}; + printf("%d\n", maxAbsoluteSum(n1, ARRAY_SIZE(n1))); // expect: 5 + printf("%d\n", maxAbsoluteSum(n2, ARRAY_SIZE(n2))); // expect: 8 +} |