-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1746. Maximum Subarray Sum After One Operation
More file actions
40 lines (38 loc) · 1.35 KB
/
Copy path1746. Maximum Subarray Sum After One Operation
File metadata and controls
40 lines (38 loc) · 1.35 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
Problem Link : https://leetcode.com/problems/maximum-subarray-sum-after-one-operation/
---------------------------------------------------------------------------------------
Complexity : Time-O(N), Memory-O(N), TimeTaken-7days
---------------------------------------------------------------------------------------
Logic :
We make a forwarddp[] and backwarddp[] and at each cell [i] we calc max sum till 'i' including [i].
After that we iterate from i...n and at each i we multiple arr[i] with itself and add forwarddp[i-1]
and backwarddp[i+1] to find the sub[] sum including that idx and also take the max and return it.
class Solution {
public int maxSumAfterOperation(int[] nums) {
int n=nums.length;
int[] fdp=new int[n];
int[] bdp=new int[n];
int rsum=0, max=0;
for(int i=0;i<n;i++){
rsum+=nums[i];
if(rsum<0)
rsum=0;
fdp[i]=rsum;
}
rsum=0;
for(int i=n-1;i>=0;i--){
rsum+=nums[i];
if(rsum<0)
rsum=0;
bdp[i]=rsum;
}
for(int i=0;i<n;i++){
max=Math.max(max, get(fdp, i-1)+nums[i]*nums[i]+get(bdp, i+1));
}
return max;
}
private int get(int[] arr, int i){
if(i<0 || i>=arr.length)
return 0;
return arr[i];
}
}