문제의 절반만 탐색하고 나머지는 효율적으로 처리
예시: 부분 집합 합 문제 (Subset Sum Problem)
시간복잡도: Θ(n × 2ⁿᐟ²)
class Solution {
int print2largest(int arr[], int n) {
// code here
int max= Integer.MIN_VALUE;
int max2 = max;
for(int i=0;i<arr.length;i++){
if(arr[i]>max){
max2=max;
max=arr[i];
}
else if(arr[i]<max && arr[i]>max2)
max2=arr[i];
}
if(max2==max || max2==Integer.MIN_VALUE)
return -1;
return max2;
}
}
Problem Description
The problem is to find the maximum sum of a contiguous subarray within a given integer array.For example, given arr = [-2, 1, -3, 4, -1, 2, 1, -5, 4], the optimal subarray is [4, -1, 2, 1], which has the maximum sum of 6.
API
public int maxSubarraySum(int[] arr)
Input
arr: An array, where each element is between -1000 and 1000.
Output:
An integer representing the maximum sum of a contiguous subarray.
Constraint
The input size N: 1 ≤ N ≤ 100
Main method for Test
public class Test {
public static void main(String[] args) {
Itm itm = new Itm();
int[] arr = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
System.out.println(itm.maxSubarraySum(arr)); // Expected output: 6
}
}
public class Itm {
public int maxSubarraySum(int[] arr) {
int maxSum = 0;
for (int i = 0; i < arr.length - 1; i++) {
int currentSum = 0;
for (int j = i + 1; j < arr.length; j++) {
currentSum += arr[j];
if (currentSum > maxSum) {
maxSum = currentSum;
}
}
}
return maxSum;
}
}