Leetcode Problem : 1331


Maximum of absolute value Expression

The code is as follows :

class Solution {
public:
    
    int get_result(vector<int> &nums){
        int n = nums.size();
        // we consider two more cases when i-j and j-i 
        
        int max1 = INT_MIN;
        int max2 = INT_MIN;
        int min1 = INT_MAX;
        int min2 = INT_MAX;
        
        int temp1,temp2;
        
        for(int i=0;i<n;i++){
            temp1 = nums[i]+i;
            temp2 = nums[i]-i;
            
            max1 = max(max1,temp1);
            max2 = max(max2,temp2);
            min1 = min(min1,temp1);
            min2 = min(min2,temp2);
        }
        return max((max1-min1),(max2-min2));
    }
    
    int maxAbsValExpr(vector<int>& a, vector<int>& b) {
        int n = a.size();
        // we consider the cases b[i] > b[j] and b[j] > b[i] 
        // but we consider a[i] > a[j] always 
        vector<int> case1;
        vector<int> case2;
        
        for(int i=0;i<n;i++){
            case1.push_back(a[i]+b[i]);
        }
        for(int i=0;i<n;i++){
            case2.push_back(a[i]-b[i]);
        }
        // we return max of the two cases
        
        return max(get_result(case1),get_result(case2));
    }
};



Summarize

I was not ready for the problem directly working with four cases as opening the modulus and taking four cases considering i>j always but later I thought instead of considering i>j. I can consider a[i]>a[j] and still get away with it. and now I have to consider I<j and i>j both cases but that's fine. It's easier to encode and put on all the cases as above in the code. Try to understand the code.

We first took a[i]+b[i] as the case when second mod open with positive and a[i]-b[i] when second mod opens with negative. and we then add them with +i and -i one time total concluding with four cases covered. and we take maximum of all of the cases to obtain our maximum.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值