diff options
-rw-r--r-- | max_abs_sum_any_subarr.c | 34 | ||||
-rw-r--r-- | max_abs_sum_any_subarr.py | 30 |
2 files changed, 64 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 +} diff --git a/max_abs_sum_any_subarr.py b/max_abs_sum_any_subarr.py new file mode 100644 index 0000000..cd58866 --- /dev/null +++ b/max_abs_sum_any_subarr.py @@ -0,0 +1,30 @@ +# 1749. Maximum Absolute Sum of Any Subarray + +""" +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' +""" + + +class Solution(object): + def maxAbsoluteSum(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + n, ans = len(nums), 0 + dp = [[0, 0] for _ in range(n)] + for i in range(n): + dp[i][0] = min(dp[i - 1][0] + nums[i], nums[i]) + dp[i][1] = max(dp[i - 1][1] + nums[i], nums[i]) + ans = max(ans, abs(dp[i][0]), dp[i][1]) + return ans + + +if __name__ == "__main__": + obj = Solution() + print(obj.maxAbsoluteSum(nums=[1, -3, 2, 3, -4])) + print(obj.maxAbsoluteSum(nums=[2, -5, 1, -4, 3, -2])) |