Maximum Profit with K Months

Company: Linkedin_31aug

Difficulty: medium

Problem Statement

Maximum Profit with K Months Problem Description A trading desk records its net result for n consecutive months. The value pnl[i] is the profit and loss of month i : a positive value is a profit, a negative value is a loss, and 0 means the month broke even. Your task is to find the maximum net profit that can be gained from any contiguous segment of months, with the constraint that the segment cannot span more than k months. A segment must contain at least one month. Complete the function getMaxProfit(pnl, k) , which returns the largest sum of a contiguous, non-empty subarray of pnl whose length is at most k . Input Format Read from standard input. Every value is on its own line. n pnl[0] pnl[1] ... pnl[n-1] k Line 1 contains n , the number of months. Each of the next n lines contains one value pnl[i] . The last line contains k , the largest number of months a segment may span. Output Format Print a single integer: the largest total of a contiguous segment of at least 1 and at most k m