leetcode

Solution to some Leetcode problems written in C++
git clone git://git.dimitrijedobrota.com/leetcode.git
Log | Files | Refs | README | LICENSE

2130.cpp (842B)


      1 class Solution {
      2     ListNode *pre_mid(ListNode *head) {
      3         ListNode *slow = head, *fast = head;
      4         while (fast->next && fast->next->next) {
      5             slow = slow->next;
      6             fast = fast->next->next;
      7         }
      8         return slow;
      9     }
     10 
     11     ListNode *reverse(ListNode *head) {
     12         ListNode *p = head, *q = nullptr, *r = nullptr;
     13         while (p) {
     14             r = q;
     15             q = p;
     16             p = p->next;
     17             q->next = r;
     18         }
     19         return q;
     20     }
     21 
     22   public:
     23     int pairSum(ListNode *head) {
     24         ListNode *pre = pre_mid(head);
     25         ListNode *head2 = reverse(pre->next);
     26 
     27         int maxi = INT_MIN;
     28         for (ListNode *p = head, *q = head2; q; p = p->next, q = q->next)
     29             maxi = max(p->val + q->val, maxi);
     30 
     31         pre->next = reverse(head2);
     32         return maxi;
     33     }
     34 };