#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <iomanip>
#include <math.h>
#include <complex>
#include <queue>
#include <deque>
#include <stack>
#include <map>
#include <set>
#include <bitset>
#include <functional>
#include <assert.h>
#define int long
#define ll long long
#define rep(i, n) for(int i = 0; i < n; i++)
#define pb push_back
#define fi first
#define se second
const int INF = 1e16;
using namespace std;

signed main() {
    int N,M; cin >> N >> M;
    int C=0;
    vector<pair<int,int>> p;
    int A[N+1]={0};
    rep(i,M){
        int a,b,c; cin >> a >> b >> c;
        a--;
        p.push_back(make_pair(a,b-1));
        A[a]+=c; A[b]-=c;
    }
    sort(p.begin(),p.end());
    bool can = true;
    rep(i,M){
        if(p[i].first<=C){
            C=max(C,p[i].second);
        }
    }
    if(C<N-1) can = false;
    rep(i,N){
        if(i){
            A[i]+=A[i-1];
        }
    }
    sort(A,A+N);
    if(!can){
        cout << -1 << endl;
    }else {
        cout << A[N-1]-A[0] << endl; 
    }

}