|
| 1 | +/** |
| 2 | + * @param {number[]} A |
| 3 | + * @return {number} |
| 4 | + */ |
| 5 | + |
| 6 | +let filterPostitives = (arr: number[]) => arr.every((i) => i > 0); |
| 7 | +let filterNegatives = (arr: number[]) => arr.every((i) => i < 0); |
| 8 | + |
| 9 | +var maxSubarraySumCircular = function (A: number[]): number { |
| 10 | + if (A.length === 0 || filterNegatives(A)) return A.sort((a, b) => b - a)[0]; |
| 11 | + if (filterNegatives(A)) return A.reduce((a, b) => a + b, 0); |
| 12 | + |
| 13 | + let i: number = 0; |
| 14 | + let max_kadane: number = kadane(A); |
| 15 | + let max_wrap: number = 0; |
| 16 | + |
| 17 | + while (i < A.length) { |
| 18 | + max_wrap += A[i]; |
| 19 | + A[i] = -A[i]; |
| 20 | + i++; |
| 21 | + } |
| 22 | + |
| 23 | + max_wrap = max_wrap + kadane(A); |
| 24 | + return max_wrap > max_kadane ? max_wrap : max_kadane; |
| 25 | +}; |
| 26 | + |
| 27 | +const kadane = (A: number[]): number => { |
| 28 | + let i: number = 0; |
| 29 | + let cur_max: number = 0; |
| 30 | + let max_so_far: number = 0; |
| 31 | + |
| 32 | + while (i < A.length) { |
| 33 | + cur_max = Math.max(0, cur_max + A[i]); |
| 34 | + max_so_far = Math.max(cur_max, max_so_far); |
| 35 | + i++; |
| 36 | + } |
| 37 | + |
| 38 | + return max_so_far; |
| 39 | +}; |
| 40 | + |
| 41 | +const sd = maxSubarraySumCircular([-3, -2, -1]); |
| 42 | +const sd1 = maxSubarraySumCircular([3, -1, 2, -1]); |
| 43 | +const sd2 = maxSubarraySumCircular([5, -3, 5]); |
| 44 | + |
| 45 | +console.log('a', sd); |
| 46 | +console.log('a', sd1); |
| 47 | +console.log('a', sd2); |
0 commit comments