Maximum subarray sum by flipping signs of at most K array elements | Python3 implementation of the approach ; Function to find the maximum subarray sum with flips starting from index i ; If the number of flips have exceeded ; Complete traversal ; If the state has previously been visited ; Initially ; Use Kadane 's algorithm and  call two states ; Memoize the answer and return it ; Utility function to call flips from index and return the answer ; Create DP array int dp [ n , k + 1 ] ; Iterate and call recursive function from every index to get the maximum subarray sum ; corner casae ; Driver Code
import numpy as np NEW_LINE right = 3 ; NEW_LINE left = 6 ; NEW_LINE dp = np . ones ( ( left , right ) ) NEW_LINE dp = - 1 * dp NEW_LINE def findSubarraySum ( ind , flips , n , a , k ) : NEW_LINE INDENT if ( flips > k ) : NEW_LINE INDENT return - 1e9 ; NEW_LINE DEDENT if ( ind == n ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if ( dp [ ind ] [ flips ] != - 1 ) : NEW_LINE INDENT return dp [ ind ] [ flips ] ; NEW_LINE DEDENT ans = 0 ; NEW_LINE ans = max ( 0 , a [ ind ] + findSubarraySum ( ind + 1 , flips , n , a , k ) ) ; NEW_LINE ans = max ( ans , - a [ ind ] + findSubarraySum ( ind + 1 , flips + 1 , n , a , k ) ) ; NEW_LINE dp [ ind ] [ flips ] = ans ; NEW_LINE return dp [ ind ] [ flips ] ; NEW_LINE DEDENT def findMaxSubarraySum ( a , n , k ) : NEW_LINE INDENT ans = - 1e9 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT ans = max ( ans , findSubarraySum ( i , 0 , n , a , k ) ) ; NEW_LINE DEDENT if ans == 0 and k == 0 : NEW_LINE return max ( a ) ; NEW_LINE return ans ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ - 1 , - 2 , - 100 , - 10 ] ; NEW_LINE n = len ( a ) ; NEW_LINE k = 1 ; NEW_LINE print ( findMaxSubarraySum ( a , n , k ) ) ; NEW_LINE DEDENT