▲ 2 r/leetcode
Somebody plz explain this question+solution (Todays contest q3)
Question: 3976. Maximum Subarray Sum After Multiplier
You are given an integer array nums and a positive integer k. You must choose exactly one subarray of nums and perform exactly one of the following operations: Return the maximum possible sum of a non-empty subarray in the resulting array. Note that the subarray chosen for the operation and the subarray chosen for the sum may be different.
Input: nums = [1,-2,3,4,-5], k = 2 Output: 14
class Solution {
public long maxSubarraySum(int[] nums, int k) {
int n = nums.length;
long best = Long.MIN_VALUE;
// mult
long A = nums[0];
long B = (long) k * nums[0];
long C = Long.MIN_VALUE / 2;
best = Math.max(A, B);
for (int i = 1; i < n; i++) {
long x = nums[i];
long kx = k * x;
long newA = Math.max(x, A + x);
long newB = Math.max(kx, Math.max(B + kx, A + kx));
long newC = Math.max(x, Math.max(C + x, B + x));
A = newA; B = newB; C = newC;
best = Math.max(best, Math.max(A, Math.max(B, C)));
}
// div
A = nums[0];
B = div(nums[0], k);
C = Long.MIN_VALUE / 2;
best = Math.max(best, Math.max(A, B));
for (int i = 1; i < n; i++) {
long x = nums[i];
long dx = div(x, k);
long newA = Math.max(x, A + x);
long newB = Math.max(dx, Math.max(B + dx, A + dx));
long newC = Math.max(x, Math.max(C + x, B + x));
A = newA; B = newB; C = newC;
best = Math.max(best, Math.max(A, Math.max(B, C)));
}
return best;
}
private long div(long x, int k) {
// if (x >= 0) return x / k;
// return (x + k - 1) / k;
if (x >= 0) return x / k;
return -((-x) / k);
}
}Multiply each number in the chosen subarray by k. Divide each number in the chosen subarray by k. When dividing a positive number by k, use the floor value of the division result. When dividing a negative number by k, use the ceiling value of the division result.1 <= nums.length <= 105 -105 <= nums[i] <= 105 1 <= k <= 105
u/Rocking_man24 — 8 days ago