diff options
-rw-r--r-- | max_ascending_subarr_sum.c | 28 | ||||
-rw-r--r-- | max_ascending_subarr_sum.py | 29 |
2 files changed, 57 insertions, 0 deletions
diff --git a/max_ascending_subarr_sum.c b/max_ascending_subarr_sum.c new file mode 100644 index 0000000..2a993e0 --- /dev/null +++ b/max_ascending_subarr_sum.c @@ -0,0 +1,28 @@ +// 1800. Maximum Ascending Subarray Sum +#include "leetcode.h" + +/* + * given an array of positive integers 'nums', return the maximum possible sum + * of an ascending subarray in 'nums'. a subarray is defined as a contiguous + * sequence of numbers in an array. + */ + +int maxAscendingSum(int *nums, int numsSize) { + int ans = 0, sum = nums[0]; + for (int i = 1; i < numsSize; ++i) { + if (nums[i] <= nums[i - 1]) { + ans = fmax(ans, sum); + sum = 0; + } + sum += nums[i]; + } + return fmax(ans, sum); +} + +int main() { + int n1[] = {10, 20, 30, 5, 10, 50}, n2[] = {10, 20, 30, 40, 50}, + n3[] = {12, 17, 15, 13, 10, 11, 12}; + printf("%d\n", maxAscendingSum(n1, ARRAY_SIZE(n1))); // expect: 65 + printf("%d\n", maxAscendingSum(n2, ARRAY_SIZE(n2))); // expect: 150 + printf("%d\n", maxAscendingSum(n3, ARRAY_SIZE(n3))); // expect: 33 +} diff --git a/max_ascending_subarr_sum.py b/max_ascending_subarr_sum.py new file mode 100644 index 0000000..54c938f --- /dev/null +++ b/max_ascending_subarr_sum.py @@ -0,0 +1,29 @@ +# 1800. Maximum Ascending Subarray Sum + +""" +given an array of positive integers 'nums', return the maximum possible sum +of an ascending subarray in 'nums'. a subarray is defined as a contiguous +sequence of numbers in an array. +""" + + +class Solution(object): + def maxAscendingSum(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + ans, sum = 0, nums[0] + for i in range(len(nums)): + if nums[i] <= nums[i - 1]: + ans = max(ans, sum) + sum = 0 + sum += nums[i] + return max(ans, sum) + + +if __name__ == "__main__": + obj = Solution() + print(obj.maxAscendingSum(nums=[10, 20, 30, 5, 10, 50])) + print(obj.maxAscendingSum(nums=[10, 20, 30, 40, 50])) + print(obj.maxAscendingSum(nums=[12, 17, 15, 13, 10, 11, 12])) |