Lead a life problem | Java program for the above approach ; Function that calculates the profit with the earning and cost of expenses ; To store the total Profit ; Loop for n number of days ; If last day , no need to buy food ; Else buy food to gain energy for next day ; Update earning per day ; Update profit with daily spent ; Print the profit ; Driver Code ; Given days ; Given earnings ; Given cost ; Given energy e ; Function call
import java . util . * ; class GFG { static void calculateProfit ( int n , int [ ] earnings , int [ ] cost , int e ) { int profit = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int earning_per_day = 0 ; int daily_spent_food = 0 ; if ( i == ( n - 1 ) ) { earning_per_day = earnings [ i ] * e ; profit = profit + earning_per_day ; break ; } if ( cost [ i ] < earnings [ i ] ) { earning_per_day = earnings [ i ] * e ; daily_spent_food = cost [ i ] * e ; profit = profit + earning_per_day - daily_spent_food ; } } System . out . print ( profit + "NEW_LINE"); } public static void main ( String [ ] args ) { int n = 4 ; int earnings [ ] = { 1 , 8 , 6 , 7 } ; int cost [ ] = { 1 , 3 , 4 , 1 } ; int e = 5 ; calculateProfit ( n , earnings , cost , e ) ; } }