File tree Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+ input : array of integer
3
+ output : largest sum of subarray
4
+ constraints :
5
+ 1) is the input array not empty?
6
+ yes. at least one el
7
+ 2) range of integers
8
+ [-10^4, 10^4]
9
+ 3) maximum lenght of input
10
+ [10^5]
11
+ >> maximum sum = 10^5 * 10^4 = 10 ^ 9 < INTEGER
12
+
13
+ sol1) brute force
14
+ nested for loop : O(n^2)
15
+ tc : O(n^2), sc : O(1)
16
+
17
+ sol2) dp?
18
+ Subarray elements are continuous in the original array, so we can use dp.
19
+ let dp[i] represent the largest sum of a subarray where the ith element is the last element of the subarray.
20
+
21
+ if dp[i-1] + curval < cur val : take curval
22
+ if dp[i-1] + cur val >= curval : take dp[i-1] + curval
23
+ tc : O(n) sc : O(n)
24
+ */
25
+ class Solution {
26
+ public int maxSubArray (int [] nums ) {
27
+ int n = nums .length ;
28
+ int [] dp = new int [n ];
29
+ int maxSum = nums [0 ];
30
+ dp [0 ] = nums [0 ];
31
+ for (int i = 1 ; i < n ; i ++) {
32
+ if (dp [i -1 ] + nums [i ] < nums [i ]) {
33
+ dp [i ] = nums [i ];
34
+ } else {
35
+ dp [i ] = nums [i ] + dp [i -1 ];
36
+ }
37
+ maxSum = Math .max (maxSum , dp [i ]);
38
+ }
39
+ return maxSum ;
40
+ }
41
+ }
You can’t perform that action at this time.
0 commit comments