Greedy algorithm that works on two ends of an array in Haskell

Viewed 164

I'm mostly curious about the general pattern that's best practice to implement algorithms where we we're marching along indices on opposite ends of an array.

Here's an example problem from leetcode.

Problem Statement

Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.

Example Solution

class Solution {
public:
    int trap(int A[], int n) {
        int left=0; int right=n-1;
        int res=0;
        int maxleft=0, maxright=0;
        while(left<=right){
            if(A[left]<=A[right]){
                if(A[left]>=maxleft) maxleft=A[left];
                else res+=maxleft-A[left];
                left++;
            }
            else{
                if(A[right]>=maxright) maxright= A[right];
                else res+=maxright-A[right];
                right--;
            }
        }
        return res;
    }
};

I've really enjoyed Haskell because of how elegant the solutions tend to be but I'm wondering if sometimes it's better to be able to fall back on imperative programming like is an option in OCaml

0 Answers
Related