DSA-L11
DSA-L11
Problem Statement: Input :arr[]= {100, 200, 300, 400}, k = 2 Output : ???
Problem Name: "Maximum Subarray for (int i = 0; i < n; i++) { for(int i = 0; i < n; i++) {
Sum" for (int j = i; j < n; j++) { int currentSum = 0;
int currentSum = 0;
Hypothetical Example
Input: An array of integers. for(int j = i; j < n; j++) {
for (int k = i; k <= j; k++) { currentSum += arr[j];
Output: maximum sum. currentSum += arr[k]; if (currentSum>maxSum){
} maxSum = currentSum;
Constraints: if (currentSum > maxSum) { }
• Time Limit: 1 second maxSum = currentSum; } Complexity?
} }
• Memory Limit: 256 MB } for (int i = 1; i < n; i++) {
• 1 <= Array Size <= 10^6 } currentSum=max(arr[i], currentSum + arr[i]);
maxSum = max(maxSum, currentSum);
• -10^9 <= Array Element <= 10^9 Complexity? }
Efficient solution: Kadane's Algorithm using DP (Ignore –ve subarray sum): Complexity is ???
FUNCTIONS FOR ALGORITHM ANALYSIS
(Seating in the class everyday) (Reading chapters of book) (Climbing a ladder quickly) (Population growth)
Execution time
Execution time
Execution time
Execution time
O(1) O(n)
2n
log2(n)
Ex.s: Array indexing, Vari Ex.s: Searching in unsorted Ex.s: Finding a word in a d Ex.s: Fibonacci sequence, T
able assignment, Basic arit array, Printing all element ictionary, Treasure hunt, et owers of Hanoi, Generatin
hmetic operations, … s of a list, … c… g all subsets of set, etc…
COMPLEXITY EXAMPLES FROM REAL LIFE
1km 1km 1km • Is it Linear?
… (Ex.1)
• Total distance over time?
Mon Tues Wed
• Per day effort?
T(n)
1E+15
i=1 j=1 k=1 i=1 j=1 1E+13
1E+11
n 1E+9
∑ n2 n3 1E+7
1E+5
i=1
1E+3
1E+1
1E-1
1E-1 1E+2 1E+5 1E+8
Interestingly, all the functions that we have listed are n
part of large class of functions called, polynomials: (In this log-log graph, the slope of the line
g(n) = a0 + a1n + a2n2 + a3n3 + ...+ adnd What is d? corresponds to the growth rate)