-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy path1746-maximum-subarray-sum-after-one-operation.js
More file actions
44 lines (38 loc) · 1.14 KB
/
1746-maximum-subarray-sum-after-one-operation.js
File metadata and controls
44 lines (38 loc) · 1.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/**
* 1746. Maximum Subarray Sum After One Operation
* https://leetcode.com/problems/maximum-subarray-sum-after-one-operation/
* Difficulty: Medium
*
* You are given an integer array nums. You must perform exactly one operation where you can
* replace one element nums[i] with nums[i] * nums[i].
*
* Return the maximum possible subarray sum after exactly one operation. The subarray must
* be non-empty.
*/
/**
* @param {number[]} nums
* @return {number}
*/
var maxSumAfterOperation = function(nums) {
const n = nums.length;
let maxWithoutSquare = nums[0];
let maxWithSquare = nums[0] * nums[0];
let result = maxWithSquare;
for (let i = 1; i < n; i++) {
const currentValue = nums[i];
const squaredValue = currentValue * currentValue;
const newMaxWithSquare = Math.max(
squaredValue,
maxWithoutSquare + squaredValue,
maxWithSquare + currentValue
);
const newMaxWithoutSquare = Math.max(
currentValue,
maxWithoutSquare + currentValue
);
maxWithSquare = newMaxWithSquare;
maxWithoutSquare = newMaxWithoutSquare;
result = Math.max(result, maxWithSquare);
}
return result;
};